I am facing an issue in converting datetime in current timzone.
I am receiving this date string from server in a format "2015-10-09T08:00:00" which is Central Time but when I convert this date time using new Date(strDate) in GMT+5 its returning me below which is incorrect.
var dateObj = '2015-10-09T08:00:00'; new Date(dateObj); // return me below Fri Oct 09 2015 13:00:00 GMT+0500 (PKT)
Another way I used is to convert by adding timezone offset and its returning me right result but defiantly failed when daylight saving activated.
dateObj2 = '2015-10-09T08:00:00'+'-06:00'; new Date(dateObj2)// return me below Fri Oct 09 2015 19:00:00 GMT+0500 (PKT)
Note that behavior of the code you wrote differs between the browsers:
new Date('2015-10-09T08:00:00').toString() // "Fri Oct 09 2015 10:00:00 GMT+0200 (Romance Daylight Time)" // Chrome 46 on Windows 8.1 // "Fri Oct 09 2015 08:00:00 GMT+0200 (Romance Daylight Time)" // Firefox 41 on Windows 8.1 // "Fri Oct 09 2015 08:00:00 GMT+0200 (Romance Daylight Time)" // IE11 on Windows 8.1 // "Fri Oct 9 08:00:00 UTC+0200 2015" // IE10 emulation // "Fri Oct 9 10:00:00 UTC+0200 2015" // IE9 emulation // on IE8 it even returns NaN!
(my timezone is Paris)
So, Firefox and IE interpret the provided date as specified as if it were in local timezone of the user, whereas Chrome interprets it as UTC, and when printed, it gets converted to user's timezone.
Checking the MDN docs, this is due to differences in EcmaScript 5 and EcmaScript 6 (2015) specifications. It seems that Chrome follows ES5 spec while Firefox and IE11 follow ES6 spec.
The date time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed. <strong>The UTC time zone is used to interpret arguments in ISO 8601 format that do not contain time zone information (note that ECMAScript 2015 specifies that date time strings without a time zone are to be treated as local, not UTC).</strong>
I wrote here
how you can leverage
moment.js or native
Intl API to make sure your date will not be converted to user's timezone (the secret is to use UTC manipulating methods).
In general it's best to <strong>always specify either both time and UTC offset, or just a UTC timestamp</strong>, to make sure your input is unambiguous.
Coming back to your example, you can use following code:
moment('2015-10-09T08:00:00-06:00') .utcOffset(+300).locale('en_gb').format("LLLL") // "Friday, 9 October 2015 19:00" cross-browser
in which you say "this is date in UTC-0600, please convert and print it as UTC+0500 (+300 minutes)". Then you can pass in which locale you want it printed (i.e. language + culture specific settings, e.g.
en_gb uses 24 hour clock while
en_us 12-hour clock) and use multitude of date formats supported by moment.js.