Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date.getUTCHours() - Different output in Chrome, Firefox and Internet Explorer

Given the following code:

var date = new Date("2014-02-26T15:52:30");
date.getUTCHours();
// Outputs
// Chrome: 15
// Firefox: 18
// IE: 18

I'm not sure which date method I should use. Date.getHours returns the correct hour in FF and IE, but incorrect in Chrome. And Date.getUTCHours() is showing me the correct date, but is not ok in both IE and FF. What are the differences anyway? What UTC date is supposed to be?

I wonder if is there a CrossBrowser native solution... I wouldn't like to use a library for such a simple thing.

like image 362
darksoulsong Avatar asked Jan 11 '23 03:01

darksoulsong


2 Answers

Chrome interpret your date var date = new Date("2014-02-26T15:52:30"); the same as var date = new Date("2014-02-26T15:52:30Z"); (notice the z, indicating the utc timezone).

FF and IE interpret var date = new Date("2014-02-26T15:52:30"); as being in the timezone of the current user, in my case, it would be var date = new Date("2014-02-26T15:52:30-05:00"); (GMT-0500)

I strongly suggest that you stick with UTC for you computing need and perform the timezone transformation when you want to show the date to the user. Timezone can become a real pain.

like image 104
Nico Avatar answered Jan 30 '23 09:01

Nico


The problem is not with getUTCHours() is with your dateString(2014-02-26T15:52:30).

As per ISO8601, it is better to have either

var date = new Date("2014-02-26T15:52:30Z");

or

var date = new Date("2014-02-26T15:52:30+00:00");

This ensures common among all browsers.

In your case it is better to have

var dateString = "2014-02-26T15:52:30" + "Z";
var date = new Date(dateString);
date.getUTCHours();
like image 45
Praveen Avatar answered Jan 30 '23 07:01

Praveen