Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...