使用locale timeshift js从字符串解析日期

时间:2014-01-22 12:32:24

标签: javascript date

我有一个字符串:“2014-01-22T09:44:06”

我想将它解析为同一个Date对象。这是我的工作:

var dateString = "2014-01-22T09:44:06";
var myDate = Date.parse(dateString);
console.log(new Date(myDate));

这是我得到的:

 Wed Jan 22 2014 13:44:06 GMT+0400 (Московское время (зима)) 

与原始字符串相比,日期对象移位4小时。如何消除这种转变?

1 个答案:

答案 0 :(得分:2)

获取时区偏移量:

您可以使用函数getTimezoneOffset(),它以分钟为单位返回您的时区偏移量:

var dateString = "2014-01-22T09:44:06";
var myDate = new Date(Date.parse(dateString));
console.log(myDate);
console.log(myDate.getTimezoneOffset());

在您的情况下,这将输出240

http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp


要获取UTC dateTime,您可以使用以下功能:

getUTCDate()           Returns the day of the month, according to universal time (from 1-31)
getUTCDay()            Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear()       Returns the year, according to universal time (four digits)
getUTCHours()          Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds()   Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes()        Returns the minutes, according to universal time (from 0-59)
getUTCMonth()          Returns the month, according to universal time (from 0-11)
getUTCSeconds()        Returns the seconds, according to universal time (from 0-59)
toUTCString()          Converts a Date object to a string, according to universal time

在您的情况下,您只需使用toUTCString()功能:

var dateString = "2014-01-22T09:44:06";
var myDate = new Date(Date.parse(dateString));
console.log(myDate);
console.log(myDate.toUTCString());
console.log(myDate.getTimezoneOffset());