9

我正在尝试将当前的 UTC 日期存储在我的数据库中。我的当地时间是晚上 9 点 11 分,这相当于世界标准时间上午 1 点 11 分。当我查看我的数据库时,我注意到正在写入 1:11 pm。我很困惑。为了在 JavaScript 中获取 UTC 时间,我使用以下代码:

var currentDate = new Date();
var utcDate = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds());
var result = new Date(utcDate);

我究竟做错了什么?

4

3 回答 3

3

一点搜索结果你可以这样做:

var now = new Date(),
    utcDate = new Date(
        now.getUTCFullYear(),
        now.getUTCMonth(),
        now.getUTCDate(),
        now.getUTCHours(),
        now.getUTCMinutes(), 
        now.getUTCSeconds()
    );

更短:

var utcDate = new Date(new Date().toUTCString().substr(0, 25));

如何将 JavaScript 日期转换为 UTC?

这是一种常用的方法,而不是创建 ISO8601 字符串,而是获取 UTC 的日期和时间。因为如果您使用字符串,那么您将无法使用 的每个本地方法Date(),并且有些人可能会为此使用正则表达式,这比本地方法要慢。

但是,如果您将其存储在某种数据库中,例如localstorage,建议使用 ISO8601 字符串,因为它还可以保存时区偏移量,但在您的情况下,每个date都转换为 UTC,所以时区真的无关紧要。

于 2012-05-21T01:31:25.813 回答
2

如果您想要本地日期对象的 UTC 时间,请使用 UTC 方法来获取它。所有 javascript 日期对象都是本地日期。

var date = new Date(); // date object in local timezone

如果您想要UTC时间,您可以尝试实现依赖toUTCString方法:

var UTCstring = date.toUTCString();

但我不会相信这一点。如果您想要 UTC 时间的 ISO8601 字符串(大多数数据库想要),那么:

var isoDate = date.getUTCFullYear() + '-' +
              addZ((date.getUTCMonth()) + 1) + '-' +
              addZ(date.getUTCDate()) + 'T' +
              addZ(date.getUTCHours()) + ':' +
              addZ(date.getUTCMinutes()) + ':' +
              addZ(date.getUTCSeconds()) + 'Z';

addZ函数是:

function addZ(n) {
  return (n<10? '0' : '') + n;
}

修改以适应。

编辑

要调整本地日期对象以显示与 UTC 相同的时间,只需添加时区偏移量:

function adjustToUTC(d) {
  d.setMinutes(d.getMinutes() + d.getTimezoneOffset()); 
  return d;
}

alert(adjustToUTC(new Date())); // shows UTC time but will display local offset

请注意上述事项。如果您说 UTC+5hrs,那么它将提前 5 小时返回一个日期对象,但仍显示“UTC+5”

将 UTC ISO8601 字符串转换为本地日期对象的函数:

function fromUTCISOString(s) {
  var b = s.split(/[-T:\.Z]/i);
  var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
  return n;
}

alert(fromUTCISOString('2012-05-21T14:32:12Z'));  // local time displayed
于 2012-05-21T02:41:23.563 回答
1
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
于 2019-01-28T15:12:11.043 回答