Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome does not return correct hour in javascript

First try is in IE 9 console:

new Date('2013-10-24T07:32:53') 
Thu Oct 24 07:32:53 UTC+0200 2013 

returns as expected

Next try is in FireFox 24 console:

new Date('2013-10-24T07:32:53')
Date {Thu Oct 24 2013 07:32:53 GMT+0200 (Central Europe Standard Time)}

Then I go into Chrome 30 console:

new Date('2013-10-24T07:32:53')
Thu Oct 24 2013 09:32:53 GMT+0200 (Central Europe Daylight Time)

But the time is 09 here, it should be 07.

Is this a bug in chrome or am I doing something wrong here?

I can't use any other format than this '2013-10-24T07:32:53' that I get by JSON from C#. I need to get the hour of this timestamp, with the getHours I get the incorect value in Chrome.

Solution:

var inputHour = input.split('T')[1];
inputHour = inputHour.substring(0, 2);
like image 577
Rumplin Avatar asked Feb 14 '23 21:02

Rumplin


1 Answers

Its no bug. The implementation of date parse function differs across browsers & so does the format of the dateString accepted by it.

However this format seems to work same across ... link:

 new Date("October 13, 1975 11:13:00")

If possible, try and use

new Date(year, month, day, hours, minutes, seconds, milliseconds)

for guaranteed results.


Regarding your format try parsing it yourself. Something like :

var str = '2013-10-24T07:32:53'.split("T");
var date = str[0].split("-");
var time = str[1].split(":");

var myDate = new Date(date[0], date[1]-1, date[2], time[0], time[1], time[2], 0);

Note (Thanks to RobG for this) : The Date constructor used above expects month as 0 - 11 & since October is 10 as per date String, the month has to be modified before passing it to the constructor.

Reference.

like image 199
loxxy Avatar answered Feb 17 '23 10:02

loxxy