Google Apps Script – Conversion from Object to String

dateformattinggoogle sheetsgoogle-apps-script

I'm trying to take information from Google Sheets and use it to send an email with the information given in sheets. I have the email part down, but when I try to editAsText to delete unwanted characters it won't allow me to. Here is what I am trying to accomplish:

var start = row[5];
returns: Fri Feb 20 2015 00:00:00 GMT+0200 (SAST)

and I want to edit that to be:

Fri Feb 20 2015

Best Answer

You're basically wanting to format a date.

I would act on the JavaScript Date object, something like:

var startDate = new Date(row[5]);
var weekDay;
switch (startDate.getDay()) {
  case 0: weekDay = "Sun"; break;
  case 1: weekDay = "Mon"; break;
  case 2: weekDay = "Tue"; break;
  case 3: weekDay = "Wed"; break;
  case 4: weekDay = "Thu"; break;
  case 5: weekDay = "Fri"; break;
  case 6: weekDay = "Sat"; break;
}
var month;
switch (startDate.getMonth()) {
  case 0: month = "Jan"; break;
  case 1: month = "Feb"; break;
  case 2: month = "Mar"; break;
  case 3: month = "Apr"; break;
  case 4: month = "May"; break;
  case 5: month = "Jun"; break;
  case 6: month = "Jul"; break;
  case 7: month = "Aug"; break;
  case 8: month = "Sep"; break;
  case 9: month = "Oct"; break;
  case 10: month = "Nov"; break;
  case 11: month = "Dec"; break;
}

var formattedDate = weekDay + " " + month + " " + startDate.getDate() + " " + startDate.getFullYear();

The variable formattedDate now holds a string like Fri Feb 20 2015.

If you want to do this by manipulating strings instead, and you're not concerned with the language settings of the spreadsheet, you could use

var startDate = row[5] + "";
var formattedDate = startDate.substring(0, 15);