Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse YYYY-MM-DD dates using the local timezone

In javascript, if I specify the date as MM/DD/YYYY, I can use new Date() to parse it as the local timezone:

>>> new Date('01/01/1970')
Date {Thu Jan 01 1970 00:00:00 GMT-0500 (EST)}

However, if I specify the date as YYYY-MM-DD, it assumes that I'm giving the date in the UTC timezone:

>>> new Date('1970-01-01')
Date {Wed Dec 31 1969 19:00:00 GMT-0500 (EST)}

Is there an easy way to tell the date parser to use the local timezone when parsing 'YYYY-MM-DD' dates? Or do I need to use .replace(/^(\d{4})-(\d{2})-(\d{2})$/, '$2/$3/$1') to fix it first?

like image 362
rampion Avatar asked Jul 27 '13 03:07

rampion


1 Answers

Date.parse behaves as follows:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

Z is the time zone offset specified as “Z” (for UTC) or either “+” or “-” followed by a time expression HH:mm

The value of an absent time zone offset is “Z”.

So in the first case, since it doesn't fit the Date Time String Format, the implementation-specific parse takes effect (which happens to be based on local time). In the second case, it does fit the DTSF, so it is parsed as if the time zone was unspecified (which is supposed to be UTC), hence the disparity

like image 86
SheetJS Avatar answered Sep 22 '22 07:09

SheetJS