Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - Date parsed with gmt + 2 hours

I always get the wrong date when I use var date = new Date(timestring), there is always +2 GMT hours.

var unsortedPlayTimes =
    [{date:'2014-08-11T09:30:00'},
        {date:'2014-08-11T08:30:00'},
        {date:'2014-08-11T08:15:00'},
        {date:'2014-08-11T08:45:00'},
        {date:'2014-08-11T12:30:00'},
        {date:'2014-08-11T10:30:00'},
        {date:'2014-08-11T11:30:00'},
        {date:'2014-08-11T07:30:00'},
        {date:'2014-08-11T13:00:00'},
        {date:'2014-08-11T23:00:00'},
        {date:'2014-08-12T00:00:00'},
        {date:'2014-08-12T01:00:00'},
        {date:'2014-08-12T05:00:00'},
        {date:'2014-08-12T09:00:00'},
        {date:'2014-08-11T14:00:00'},
        {date:'2014-08-11T18:30:00'},
        {date:'2014-08-11T13:00:00'}];

function SortandFilterPlayTimes (allPlayTimes) {
    var filteredPlayTimes = [];
    $.each(allPlayTimes, function(index, value) {
        var date = new Date(value.date);

        if ($.inArray(date,filteredPlayTimes) === -1) {
            filteredPlayTimes.push(date);
        }
    });
};

Why is JavaScript always adding this +2 hours ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're using the ISO-8601 formatting of dates while omitting the timezone, this makes the parsing consider the timezone as UTC in ES5 (this will be different in ES6 : strings in ISO format will be considered as local too when the timezone isn't provided).

If you want the date to be parsed with your local timezone in ES5, you might change the format to a not ISO one :

var date = new Date(value.date.replace(/T/,' '));

But you might also want to check you really want the date to be parsed depending on the user's timezone, this is most often a bad idea. The usual good solution is to send the timezone or to send the date as a unix timestamp (what you get with date.getTime()).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...