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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With