73763

Javascript convert timezone issue

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)

I appreciated if anyone help OR suggest me efficient way to handle to timezone conversion with daylight saving in JavaScript?

Thank you.

Answer1:

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.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#ECMAScript_5_ISO-8601_format_support (emphasis mine)

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>

Unfortunately Date object in JavaScript is famous for its quirks and cross-browser inconsistencies, particularly on ambiguous input.

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.

Recommend

  • Convert javascript date to json date format
  • Angular and Breeze edit Date object
  • Insert into mysql using php / html form - not working
  • How should I store date/time objects in SQL?
  • Guess timezone name for custom date
  • Facebook Events and timezones, how to convert UTC datetime to what facebook expects?
  • Print in single Pthread
  • JavaScript Date Bug February 2014
  • Using an R Markdown Document as a source for functions
  • HTML file fetched using 'wget' reported as binary by 'less'
  • Memory usage differs greatly (and strangely) between frontend and backend
  • Using python to determine if a timestamp is under daylight savings time
  • Where can in find the locale objects for d3.js for different countries
  • RewriteCond and rewriteRule to redirect depending on the domain
  • Failed to execute goal net.alchim31.maven:scala-maven-plugin:3.2.2
  • Making more efficient Matlab ismember for large matrices: any faster suggestion than logical indexin
  • string.IsNullOrEmpty() Doesn't Seem to Work on a String within a Class within a Class
  • MySQL: Difference between `… ADD INDEX(a); … ADD INDEX(b);` and `… ADD INDEX(a,b);`?
  • Certain Arabic text gets incorrectly shown while other Arabic text gets showed normally?
  • Is there a way to call library thread-local init/cleanup on thread creation/destruction?
  • Accessing Rows In A LINQ Result Without A Foreach Loop?
  • .NET video play library which allows to change the playback rate?
  • Responsive design method for collapsing a div
  • Problems with toDataURL HTML5 other ways to get canvas data?
  • PayPal API Listener Website Payments Standard URI
  • Detecting null parameter in preprocessor macro
  • Repository Browser Only - \"Repository moved permanently to… please relocate”
  • Hide HTML elements without javascript, only CSS
  • Is playing sound in Javascript performance heavy?
  • Chrome doesn't support silverlight anymore? How to solve this?
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Ajax jQuery multiple calls at the same time - long wait for answer and not able to cancel
  • C# - Serializing and deserializing static member
  • Volley JsonObjectRequest send headers in GET Request
  • Sony Xperia Z Tablet not found by adb
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • How do you join a server to an Active Directory (domain)?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value