javascriptobjectgoogle-apps-scriptgoogle-sheetsdatestamp

JavaScript mail function - strip datestamp portion from string


I am working with Google apps script and have a working function that sends emails based on a custom menu. The function that sends them is using a getRowsData() function to gather all the columns as objects, concatenating those objects into strings, and sending them via the htmlBody parameter, like this:

MailApp.sendEmail({
  to: recipient,
  subject: emailSubject,
  htmlBody: message,
});

The message variable holds text and concatenated variables, with HTML formatting applied to construct the email. There is a portion that creates an Ordered list based on some other variables, and one of them is the date, which is pulled from a column within the sheet:

var message = "Other stuff here....Then"+
"<ol>"+
  "<li>"+desc+"</li>"+
  "<li>"+actions+"</li>"+
  "<li>"+datesPer+"</li>"+
  "<li><strong>Additional notes:</strong>"+actionNotes+"</li>"+
"</ol>"+
"More stuff below....";

When the email is sent, the datesPer variable prints out a bunch of other characters after the actual date. I'm assuming it's because the form attached to the sheet is inserting a datestamp:

3. Date: Tue Nov 08 2016 00:00:00 GMT-0800 (PST)

The 00:00:00 GMT-0800 (PST) is what I would like to change, with the zeroes using a regular time format (8:00 AM for example) and everything after that deleted. The array storing the dates has them formatted the way that they are coming out in the email, so this is a case of me telling the code exactly what I want, without telling it exactly what I want. I saw a Utilities.formatDate() class in the documentation, but it doesn't appear that I can call this into the script editor in sheets (Or I'm going about it wrong.)

If I missed a setting in the form, and this is just a checkbox somewhere, please educate me :) If it's something I can fix with code, I'd love some suggestions.

Thanks!


Solution

  • You can use javascript Date object functions to get the time from your date string. You can find more details about it here: http://www.w3schools.com/js/js_date_methods.asp

    Your script should have a line like this:

    datesPer = "Date:" + TimeArray[0]
    

    You can modify the date by creating a new Date object using the value from the array like so

    var dateFromSheet = new Date (TimeArray[0])
    var day = dateFromSheet.getDay() //(Returns 0- Sunday, 6 - Saturday)
    var time = dateFromSheet.getHour() + ":" + dateFormSheet.getMinutes()
    

    The values that you get from the above can be formatted to your liking and pass it to datesPer variable.