用gmt解析的日期+ 2小时 [英] Date parsed with gmt + 2 hours
问题描述
使用 var date = new Date(timestring)
时,我总是得到错误的日期,总是有+2 GMT小时.
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);
}
});
};
为什么JavaScript总是将这两个小时加在一起?
Why is JavaScript always adding this +2 hours ?
推荐答案
您正在使用 ISO-8601格式化日期,同时省略时区,这使解析在ES5中将时区视为UTC (在ES6中会有所不同:如果未提供时区,ISO格式的字符串也将被视为本地).
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).
如果您希望将日期与ES5中的本地时区一起解析,则可以将格式更改为非ISO格式:
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/,' '));
但是您可能还想根据用户的时区检查您是否真的要解析日期,这通常是一个坏主意.通常,好的解决方案是发送时区或将日期作为unix时间戳发送(使用 date.getTime()
获得的信息).
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()
).
这篇关于用gmt解析的日期+ 2小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!