Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...