简体   繁体   中英

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM