How to format Date in Google Script - google-apps-script

I am trying to write a small Google Script which takes data from some cells of Google Sheet and Paste it in the GMAIL.
However, while pasting the 'Date Values' it always displays it in the following manner:-
Mon Apr 15 2019 00:00:00 GMT+0530 (IST)
Fri Apr 26 2019 00:00:00 GMT+0530 (IST)
But I need the dates in an appropriate way i.e.
"Mon Apr 15 2019" or
"Fri 04/26/2019"
I gone through these possible options i.e. Utilities.formatDate & .Split but somehow I am not able to write these codes appropriately. Can you please help me with this matter. Below I have mentioned the entire issue in detail.
My Code
function temp2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName('Sheet1');
var templateSheet = ss.getSheetByName('Sheet2');
var emailTemplate2 = templateSheet.getRange("G1").getValue();
var rec = templateSheet.getRange("C1").getValue();
var sub = templateSheet.getRange("D1").getValue();
var date = templateSheet.getRange("E1").getValue();
// Logger.log(rec);
MailApp.sendEmail(rec, sub, emailTemplate2);
}
here var date = templateSheet.getRange("E1").getValue(); is the part of code which picks value of date.
Do let me know if you need more details in this regard
Regards,
Alok

Requirement:
Format date value from cell in Google Apps Script.
Solution:
Pass value to date constructor new Date() then format using Utilities.formatDate().
// pass date to date constructor
var date = new Date(templateSheet.getRange("E1").getValue());
// "Mon Apr 15 2019" example
var formattedDate = Utilities.formatDate(date, "GMT+0", 'E MMM dd yyyy');
// "Fri 04/26/2019" example
var formattedDate = Utilities.formatDate(date, "GMT+0", 'E MM/dd/yyyy');
Note: I've set this to timezone "GMT+0" by default, you can change this to whichever time zone you need.
References:
new Date() for date constructor.
Utilities.formatDate() for formatting dates in Google Apps Script.
SimpleDateFormat for date format strings.

Related

Why is Google Sheets or Google App Script not providing me with the same time values as what is displayed?

Context
I have an RESTful API built with Google App Script on a Google Sheet. One of the doGet() requests will retrieve data from one of the sheet tabs stored in a traditional column/row (database-like) fashion (structure described later). Simply, the doGet() will evoke another function to get the data, then it will encode that data into JSON response for the client.
The Data in the Sheet
This is what the data looks like on the sheet.
DATE
LOCATION
SHIFT
NAME
START
END
4-1-2021
WP
KANTOOR I
Danny
9:00
17:00
4-1-2021
BK
BAKKERIJ I
Naomi
9:00
17:00
4-1-2021
CK
KOK I
Fidel
7:00
16:00
...
...
...
...
...
...
The Google App Script Function
The function iterates over the table above and gets the the row that matches the name passed into the function against the name in the NAME column.
function getContactSchedule(name) {
var payload = { schedule: [] };
var rows = scheduleSheet // schedule sheet is the .getSheetByName() for the above sheet
.getRange(2, 1, scheduleSheet.getLastRow(), scheduleSheet.getLastColumn())
.getValues();
for (var i = 0, l = rows.length; i < l; i++) {
var shift = { date: null, location: null, shift: null, name: null, start: null, end: null };
const scheduleItem = rows[i];
if (name != scheduleItem[3]) continue;
shift.date = scheduleItem[0];
shift.location = scheduleItem[1];
shift.shift = scheduleItem[2];
shift.name = scheduleItem[3];
shift.start = scheduleItem[4];
shift.end = scheduleItem[5];
shift.index = i;
// add to payload.
payload.schedule.push(shift);
}
return payload;
}
Problem
When I get the data in the table and convert it to the Object, I see different timestamps than store (other the timezone or epoch difference).
Here is some driver code:
function testGetContactSchedule() {
var data = getContactSchedule('Danny')['schedule'];
console.log(data[0]);
}
Output:
{ date: Sun Jan 03 2021 16:00:00 GMT-0700 (Mountain Standard Time),
location: 'WP',
shift: 'KANTOOR I',
name: 'Danny',
start: Sat Dec 30 1899 01:40:28 GMT-0700 (Mountain Standard Time),
end: Sat Dec 30 1899 09:40:28 GMT-0700 (Mountain Standard Time),
canUpdate: true,
index: 0 }
The first row of the table is the same data here, just converted into the JS Object. But the time difference is unusual.
DATE
LOCATION
SHIFT
NAME
START
END
4-1-2021
WP
KANTOOR I
Danny
9:00
17:00
Question
Why is there this unusual difference in time? As if it adds about 40 minutes to the time stamp rather than the 00:00 that I think I'm expecting?
The reason you are receiving the date Sat Dec 30 1899 01:40:28 GMT-0700 is because getValues returns an object of type date. However, this object is adapted from Sheets - 12/30/1899 0:00:00 representing the zero mark of time for it.
Therefore, a solution for this is to use getDisplayValues instead of getValues. This will end up returning the actual values displayed in Sheets.
Reference
Apps Script Class Range - getDisplayValues().
dates are always a bit complex in JS.
You can try this script, it worked for me. You can change the format of the date and also the time zone.
const sheet = SpreadsheetApp.openById("ZZZZZZZ");
const data = sheet.getSheetByName("XXX").getDataRange().getValues();
function getData(){
data.forEach(dates => {
var date = Utilities.formatDate(new Date(dates), "GMT+2", "MM/dd/yyyy");
console.log(date);
})
}
Sheet:
Output:

getRange.getValue returning wrong date from Google sheets

var sheetdate = activeSheet.getRange(x, y).getValue() I was using this line to read a date from google sheets. Date in sheets is 2021-02-01. But sheetdate is returning value Sun Jan 31 13:30:00 GMT-05:00 2021. Actual output should be Mon Feb 1 17:35:00 GMT 05:30
This is an issue with the timezone as Sourcerer mentioned.
There are many possible answers to this one but I prefer this one, formatting the date using Utilities as you can control your output:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
date = sheet.getRange(1, 1).getValue()
Logger.log(date);
Logger.log(SpreadsheetApp.getActive().getSpreadsheetTimeZone());
Logger.log(Utilities.formatDate(date, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "E MMM dd HH:mm:ss z yyyy"));
}
For the formatting, the one I used above "E MMM dd HH:mm:ss z yyyy" is trying to emulate the default date output. See the reference below and feel free to modify based on what you need to output for the date
Referenece:
SimpleDateFormat

google app script how to get date in string date(spread sheet)

I want to compare the date that was created in the spreadsheet with a specific date.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var spreaddate = ss.getSheetByName("sheet123").getRange("B2").getValue();
//--> Thu Dec 12 00:00:00 GMT+09:00 2019
var comparedate = new date(yyyy-mm-dd)//somting like this
if(spreaddate > comparedate){
do something
}
The spreaddate is not recognized as a date.
Even if I try to convert it to a date, it's hard because it's written in letters, not numbers like Thu Dec.
What should I do?
I think the problem is that you're not correctly defining your comparedate. You need to use a capital 'D' new Date().

How to convert "yyyy-mm-dd" Google Forms field to Date type?

In Google Apps Script, I try to insert Calendar event after form submit.
On FormSubmit I have the following code:
var startDate = formData.namedValues["From day"];
var endDate = formData.namedValues["To day"];
var cal = CalendarApp.getCalendarById("mycalendarid");
var startDatecal = new Date(startDate);
var endDatecal = new Date(endDate);
Logger.log(startDate);
Logger.log(endDate);
Logger.log(startDatecal);
Logger.log(endDatecal);
cal.createEvent(name, startDatecal, endDatecal);
The problem is the format of the date in spreadsheet "yyyy-mm-dd" is not recognized by Date() function, here's the log:
[15-01-02 12:50:08:752 CET] [2015-01-02]
[15-01-02 12:50:08:753 CET] [2015-01-03]
[15-01-02 12:50:08:753 CET] Thu Jan 01 01:00:00 GMT+01:00
[15-01-02 12:50:08:754 CET] Thu Jan 01 01:00:00 GMT+01:00 1970
My questions are:
how to properly get the dates from the form in the way it is not dependand on the spreadsheet's locale settings? If it's not possible, how to convert "yyyy-mm-dd" format to something understandable by Date() function?
how to convert it to Date object then?
startDate and endDate look like an array, use the first element i.e.
var startDate = formData.namedValues["From day"][0];
var endDate = formData.namedValues["To day"][0];
that way you pass a string in the yyyy-mm-dd format which is what the in-built JS Date object should understand.

Getting day of the week not working when using setNumberFormat

I would like programably enter the date into a cell and format it to include the Day of the week (Mon, Tue, Wed,...). If I use the .setNumberFormat method (which I would prefer to do because it keeps the info as a date), the simpleDateFormat for Day of the week does not work. If I use Utilities.formatDate I can use 'EEE, MM/dd' and it will show up correctly, but I lose the date format.
function setformat(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lab = ss.getSheetByName("test2");
// This is what I want to use but the day of the week 'EEE' doesn't work
var todaySNF = new Date();
lab.getRange("a1").setValue(todaySNF);
lab.getRange("a1").setNumberFormat('EEE, MM/dd'); // Should read Wed, 09/23 but reads EEE, 09/23 instead.
var cellA1asDate = new Date(lab.getRange("a1").getValue());
Logger.log(cellA1asDate);}
use this instead :
lab.getRange("a1").setNumberFormat('DDD, MM/dd');