当我运行此代码时,第一个日期显示在GMT中,第二个日期显示在BST中。为什么是这样? Date.UTC
的呼叫除了一个已更改的数字(月份数字)之外是相同的。对我来说,这不应该保证时区的变化。请注意我现在在伦敦,所以不知何故,第二次约会似乎是在当地时间返回。为什么两个不同日期的时区不同?
var date1 = new Date(Date.UTC(2005,0,5,4,55,55));
alert(date1); // Wed Jan 05 2005 04:55:55 GMT+0000 (GMT)
var date2 = new Date(Date.UTC(2005,5,5,4,55,55)); // <-- 0 has been replaced by 5
alert(date2); // Sen Jun 05 2005 05:55:55 GMT+0100 (BST)
答案 0 :(得分:1)
使用Date.UTC(),仅使用UTC设置日期。
默认情况下,使用本地时间显示Javascript日期。
因此,如果您希望以UTC格式查看日期, 您不能只使用默认的toString()实现,因为它将使用localtime版本。
但您可以使用UTC变体进行显示。例如。 toUTCString()
以及toISOString()
。
var date2 = new Date(Date.UTC(2005,5,5,4,55,55));
//if you say live in the UK, this date in localtime is
//British Summer Time,..
//eg. Sun Jun 05 2005 05:55:55 GMT+0100 (GMT Summer Time)
//if your running this script from another country
//your likely to see something different.
console.log(date2.toString());
//here we show the date in UTC, it will be same
//whatever country your running this from
//eg. Sun, 05 Jun 2005 04:55:55 GMT
console.log(date2.toUTCString());
//for an easier to parse date,
//eg. 2005-06-05T04:55:55.000Z
console.log(date2.toISOString());