如何为UTC中的当前时间创建新的javascript日期对象



我正在尝试托管一个带有倒计时计时器的应用程序,该计时器将来会从给定的UTC日期和时间中减去当前的UTC日期与时间。但问题是new Date()new Date(Date.now())等,我一直使用休息了几个小时的本地时间。如何创建一个以UTC为当前时间的新Date对象?

let date = new Date()
date = date.toUTCString().slice(0, date.toUTCString().length - 13);
let time = "17:00:00"    
// this is the UTC time of the event, this works hosted
// locally this has to be "12:00:00"
const timeLeft = new Date(`${date} ${time}`) - new Date();
const hoursLeft = Math.floor((timeLeft / (1000 * 60 * 60)));
const minutesLeft = Math.ceil((timeLeft / 1000) / 60 % 60);
// I'm trying to get a consistent hoursLeft on both local and hosted machines

我可能只会使用moment.js来避免这个问题并简化代码,但我仍然很想知道答案。

如何为UTC中的当前时间创建新的javascript日期对象?

这两者中的任何一个都能做到,而且只能做到。

const d = new Date();

const d = new Date(Date.now());

在内部,Date对象只存储一个值,即自1970-01-01T00:00:00.000Z(Unix时间戳(以来的毫秒数,该值以UTC表示,因此Date对象本身也以UTC表示;从new Date()获取当前Date对象或从Date.now()获取当前Unix时间戳的想法也以UTC为单位。

您可能会感到困惑,因为当将Date对象显示为字符串时,您看到的是等效的本地时间,例如当看到来自console.log(d.toString())的输出时(或者在某些环境中仅来自console.log(d),但并非全部,因为这种行为是未定义的(。本地时区来自toString调用期间的运行时环境——它不存储在Date对象本身中。

如果要查看UTC时间,请改为使用console.log(d.toISOString())toISOString函数始终以ISO 8601格式显示UTC日期和时间。

这样做:

var i=new Date();
var d = new Date(i.getUTCFullYear(), i.getUTCMonth(), i.getUTCDate(), i.getUTCHours(), i.getUTCMinutes(), i.getUTCSeconds());

以创建当前时间为UTC的新Date对象。

更新
这也适用:

var d = new Date();
var n = d.toUTCString();

最新更新