1

I am trying to obtain a date by feeding year, month and day parameters to new Date(). Like so:

Logger.log(dates[i]);
var date = dates[i].trim();
Logger.log(date);
var dateMDY = date.split("/");
Logger.log(dateMDY);
Logger.log(parseInt(dateMDY[2], 10));
Logger.log(parseInt(dateMDY[0], 10));
Logger.log(parseInt(dateMDY[1], 10));
var finalDate = new Date(parseInt(dateMDY[2]), parseInt(dateMDY[0])-1, parseInt(dateMDY[1]));
Logger.log(finalDate);

Here is the log output:

[16-09-12 09:57:57:047 PDT] 09/24/2016
[16-09-12 09:57:57:048 PDT] 09/24/2016
[16-09-12 09:57:57:048 PDT] [09, 24, 2016]
[16-09-12 09:57:57:049 PDT] 2016.0
[16-09-12 09:57:57:050 PDT] 9.0
[16-09-12 09:57:57:050 PDT] 24.0
[16-09-12 09:57:57:051 PDT] Wed Dec 31 19:00:00 GMT-05:00 1969
[16-09-12 09:57:57:711 PDT]  09/28/2016
[16-09-12 09:57:57:712 PDT] 09/28/2016
[16-09-12 09:57:57:712 PDT] [09, 28, 2016]
[16-09-12 09:57:57:713 PDT] 2016.0
[16-09-12 09:57:57:713 PDT] 9.0
[16-09-12 09:57:57:714 PDT] 28.0
[16-09-12 09:57:57:715 PDT] Wed Dec 31 19:00:00 GMT-05:00 1969

What am I doing wrong?!

Flame of udun
  • 2,136
  • 7
  • 35
  • 79
  • 3
    I'm not able to [reproduce your problem.](https://jsfiddle.net/32epzfj0/1/) Are there other details you aren't including? Could you reduce the example to the smallest possible code to recreate the issue? – Mike Cluck Sep 12 '16 at 17:14

1 Answers1

6

The problem is parseInt("09") with no radix.

Shockingly, parseInt in Google Apps Script (which isn't, quite, JavaScript) still treats a leading 0 in a string as meaning it's in octal. (This was never in the JavaScript spec, but some engines implemented it; eventually it was explicitly forbidden.) Of course, octal has no 9 digit, and parseInt stops parsing at the first non-parseable digit, returning NaN if there were no parseable digits. So parseInt("09") returns NaN and you end up passing that into the constructor as the month (since NaN - 1 is NaN).

If you specify a decimal radix (which you did in your Logger.log statements of the individual parts, but not when actually building the date!), it will parse "09" as 9:

Logger.log(dates[i]);
var date = dates[i].trim();
Logger.log(date);
var dateMDY = date.split("/");
Logger.log(dateMDY);
Logger.log(parseInt(dateMDY[2], 10));
Logger.log(parseInt(dateMDY[0], 10));
Logger.log(parseInt(dateMDY[1], 10));
var finalDate = new Date(parseInt(dateMDY[2], 10), parseInt(dateMDY[0], 10)-1, parseInt(dateMDY[1], 10));
// -----------------------------------------^^^^----------------------^^^^-------------------------^^^^
Logger.log(finalDate);

Output:

[16-09-12 19:02:15:137 BST] 09/24/2016
[16-09-12 19:02:15:138 BST] [09, 24, 2016]
[16-09-12 19:02:15:138 BST] 2016.0
[16-09-12 19:02:15:139 BST] 9.0
[16-09-12 19:02:15:140 BST] 24.0
[16-09-12 19:02:15:140 BST] Sat Sep 24 00:00:00 GMT+01:00 2016

(Figured this out by stepping through the code in the GAS debugger.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875