LLAE
LLAE

Reputation: 33

How to read a time in googlespreadsheet with google apps script?

After hours spent to identify a rational or a solution, my hope is now with this community !

I'm desesperatly trying to get ("read") a time entered by user in a google spreasheet and to use it correctly in a google apps script for example to create google calendar event.

The desired format is "HH:mm"

My starting point is the google apps script example provided on https://developers.google.com/apps-script/quickstart/forms

From this example I modified the parameters of the spreasheet (sorry for the french!) using the "Change locale and time zone" instructions : settings illustration

I also changed the display format of the columns 'C' and 'D' to not have the AM/PM put in the initial example:

Start Time  End Time
13:00:00    14:55:00
13:00:00    14:55:00
...

To enable debug in script editor, I removed "_" at the end of setUpConference (line 14).

I launched the script "setUpConference" in debug to check the values read from the datasheet. My surprise is to have for the first data line

Ethics for monsters 5/15/2013   13:00:00    14:55:00    Rm 323: Minotaur's Labyrinth

the corresponding data of the variable "session"

["Ethics for monsters", (new Date(1368568800000)), (new Date(-2209115361000)), (new Date(-2209108461000)), "Rm 323: Minotaur's Labyrinth"]

and sessions[2] is showned in the script editor as: Sat Dec 30 1899 13:50:39 GMT+0100 (CET)

I understand that having only "time" (HH:mm), the date is incomplete (so the 1899 day) but how to obtain the time "13:00:00" rather than this strange "13:50:39" ?

Ps: my calendar time zone is also GMT+0100 (CET)


some edits with more information:

Upvotes: 3

Views: 4295

Answers (1)

Jared Pinkham
Jared Pinkham

Reputation: 501

As linked in some of the comments sheets and JS use different date epochs and they don't always play nice.

change the var values = range.getValues(); to var values = range.getDisplayValues();

this will force it to grab the cells values as string.

changing your date join function as follows will make it handle the strings(may need to ensure the dates in your spread sheet to have leading zeros):

function joinDateAndTime(date, time) {
  var t = new Date(date);
  t.setHours(parseInt(time.substring(0, 2)));
  t.setMinutes(parseInt(time.substring(3, 5)));
  return t;
}

Upvotes: 5

Related Questions