aNewb
aNewb

Reputation: 198

JSON string to date with Javascript in Google Apps Script editor

I am working through w3schools, particularly https://www.w3schools.com/js/js_json_parse.asp

I ran this example and got an unexpected result

  let dashText = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
  let objD = JSON.parse(dashText);
  console.log("objD: ", objD);
  objD.birth = new Date(objD.birth);
  console.log("objD.birth: ", objD.birth);

3:09:04 PM  Info    objD:  { name: 'John', birth: '1986-12-14', city: 'New York' }
3:09:04 PM  Info    objD.birth:  Sat Dec 13 1986 18:00:00 GMT-0600 (Central Standard Time)

Note the difference in the dates. I then changed the dashes to slashes out of curiosity and the date was correctly determined from the string.

  let slashText = '{ "name":"John", "birth":"1986/12/14", "city":"New York"}';
  let objS = JSON.parse(slashText);
  console.log("objS: ", objS);
  objS.birth = new Date(objS.birth);
  console.log("objS.birth: ", objS.birth);

3:09:04 PM  Info    objS:  { name: 'John', birth: '1986/12/14', city: 'New York' }
3:09:04 PM  Info    objS.birth:  Sun Dec 14 1986 00:00:00 GMT-0600 (Central Standard Time)

Can anyone explain the results?

Upvotes: 0

Views: 218

Answers (1)

Mark Weinhold
Mark Weinhold

Reputation: 98

Javascript parses DateTime strings differently based on how the string is formatted. The dashes are parsed to ISO date, i.e. international time. You can see this when it tries to handle the timezone conversion, where it sets the time to 18:00:00 to account for the 6 hour shift from Universal Time. Slashes are parsed as just the date, and doesn't try to adjust the time based on timezones.

Here's a w3schools link that goes over this in more detail.

Upvotes: 3

Related Questions