Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect Javascript Date in Chrome vs Firefox

I'm getting incorrect dates in Chrome...

My code looks like this..

Title contains "2013-06-14T00:00:00", it was a DateTime in C# returned from WebAPI

As you can see here on both browsers.. enter image description here

When I add it to a new javascript date like this.. var dt = new Date(title)

I get different dates in different browsers... enter image description here

Example - http://jsfiddle.net/RvUSq/

like image 872
jaekie Avatar asked Dec 02 '22 22:12

jaekie


2 Answers

Looks like Firefox is assuming this datetime format without timezone is local time and Chrome/Webkit is assuming it's UTC.

If the datetime returned from the api is UTC, simply append a "Z" to the end of the string, so it becomes "2013-06-14T00:00:00Z", which indicates the time is in UTC, then you will get the same result in the two browsers.

like image 146
Ye Liu Avatar answered Dec 14 '22 12:12

Ye Liu


Convert timestamp to ISO 8601 formatted string in C#, for e.g

var title = "14 JUN 2013 00:00:00" // printed from C#

Then use Date constructor

var date = new Date(title);

If you don't specify timezone the local timezone in the client machine will be set to the given time. If you specify the timezone, needed calculations will be done to convert the date to local timezone.

var title = "14 JUN 2013 00:00:00";
var date = new Date(title); // Fri Jun 14 2013 00:00:00 GMT+0530 (IST)

var title = "14 JUN 2013 00:00:00 GMT";
var date = new Date(title); // Fri Jun 14 2013 05:30:00 GMT+0530 (IST)

var title = "14 JUN 2013 00:00:00 GMT-0400";
var date = new Date(title); // Fri Jun 14 2013 09:30:00 GMT+0530 (IST)

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

like image 21
Diode Avatar answered Dec 14 '22 12:12

Diode