简体   繁体   中英

javascript create date without daylight savings conversion

when i create date using date constructor new Date('2015','12'), it results in Fri Jan 01 2016 00:00:00 GMT-0500 (Eastern Standard Time). But don't it to assume that what date i am providing is already applied daylight conversion and create date object for december 2015, instead of jan 2016

When creating a date using the Date constructor, the time zone of the host system is almost always used (per ECMA-262). The only exception is when a number (interpreted as a time value, ie milliseconds since the ECMAScript epoch) is provided, or an ISO 8601 format string with a time zone. Even then, the internal time value of the Date (ie milliseconds since the epoch) is calculated in UTC and the host system time zone offset used for the non–UTC methods like getHours , getMinutes , etc.

Also, the timezone offset of the current systems settings are used for historical dates. So if the host is set for daylight saving, it will be applied to dates at times before daylight saving was implemented. Also, historical changes to daylight saving changeover dates and times (and even value) are not applied. The currents settings are assumed to always apply for past and future dates.

So all of the following will apply the timezone offset of the host system when creating a date for 3 February, 2016:

new Date('2/3/2016'); // US format is assumed by most browsers.
                      // May also create an invalid Date
new Date(2016, 1, 3); // months are zero indexed so 1 is February
new Date('2016-02-03T00:00:00'); // note missing time zone

However, the following will be treated as UTC (or invalid):

new Date('2016-02-03');  // contrary to ISO 8601, missing time zone for this
                         // format only is assumed to be UTC
new Date('2016-02-03T00:00:00Z'); // Note has a time zone of GMT

If you want to reliably create a Date for a specific instant in time from a string, you must provide a string with the time zone offset. Then parse it yourself since parsing of date strings is largely implementation dependent and varies across implementations. The best format to use is ISO 8601 extended so something like:

'2016-02-03T00:00:00-0800'

which represents the same instant in time no matter what the settings of the host system are. You just need to reliably parse it.

There are many good libraries for parsing and formatting, or you can write your own small functions for particular parse and output formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM