Search code examples
javascriptdatetimetimezoneutc

Ambiguous behavior of javascript new Date() constructor for same different formatted string


My local time zone is (UTC+06:00) Dhaka. In my own time zone I didn't find this problem. But changing the time zone to (UTC -12:00) International Date Line West in my pc,

new Date(["2014","01","01"]) is giving me output Wed Jan 01 2014 00:00:00 GMT-1200 (GMT-12:00).

new Date("2014-01-01") is giving me output Tue Dec 31 2013 12:00:00 GMT-1200 (GMT-12:00).

Why this is happening? Shouldn't ["2014","01","01"] and "2014-01-01" suppose to give same output?


Solution

  • This is due to new Date("2014-01-01") being created through the Date parse which considers this date to be UTC and then apply the timezone but new Date(["2014","01","01"]) is treated as literal values for each of the parameters in the constructor for your timezone. Although as mentioned in one of the comments below the format new Date(["2014","01","01"]) does not conform to RFC and hence provides different results depending on the browser.

    from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

    Perhaps what you are after is new Date(Date.UTC(2014,01,01)); Date.UTC in order to create a consistent date that is not bound to the user's configuration.