I have this problem. I have this date with this format
var datestring = "2017-10-30T15:03:10.933044Z";
If I write my code like this
var d = new Date(datestring);
I obtaine
Mon Oct 30 2017 16:03:10 GMT+0100 (ora solare Europa occidentale)
because there is one hour of a daylight in italy now. Nevertheless, I would like to have the same hour of 'datestring' (15, and not 16). Could you help me?
thank you very much
答案 0 :(得分:1)
您的输入字符串是ISO-8601格式。在这种格式中,末尾的Z
表示时间戳是基于UTC的。
您可以使用.toUTCString()
方法获得更加人性化的基于UTC的字符串表示。
var datestring = "2017-10-30T15:03:10.933044Z";
var d = new Date(datestring);
var s = d.toUTCString();
console.log(s) // "Mon, 30 Oct 2017 15:03:10 GMT"
如果您想要特定格式的字符串,请考虑使用Moment.js等库。
答案 1 :(得分:1)
根据ECMA-262,如果您想将ISO 8601格式的UTC时间戳视为本地,只需删除Z.但是,如果当地时区不是GMT + 0000,它现在将代表不同的时刻。< / p>
此外,建议不要使用内置解析器(请参阅Why does Date.parse give incorrect results?),因为某些浏览器仍会将其视为UTC(例如Safari 11)或可能无效。您应该编写自己的函数来解析字符串,或者使用库。有很多很好的解析和格式化库。
var s = '2017-10-30T15:03:10.933044Z';
var d = new Date(s.replace(/z/i,''));
console.log(d.toString());