JavaScript 中的 UTC 时间

UTC Times in JavaScript

本文关键字:时间 UTC 中的 JavaScript      更新时间:2023-09-26

我正在尝试获取当前的UTC日期以存储在我的数据库中。 我的当地时间是晚上 9:11。这相当于 UTC 时间凌晨 1:11。当我查看我的数据库时,我注意到下午 1:11 正在写入。我很困惑。为了在 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);

我做错了什么?

搜索结果可以做到这一点:

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,因此时区真的无关紧要。

如果需要本地日期对象的 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
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);