使用 UTC/GMT+0 作为纪元忽略本地时区纪元,从特定日期获取当前时间戳

Get current timestamp from specific date using UTC/GMT+0 as epoch ignoring local time zone epoch

我已经从这个社区尝试了很多,但似乎没有针对我的案例的超特定场景。

所以基本上我有一个 yyyy-mm-dd 格式的字符串。我使用日期方法来调整它并在日期上添加时间以使其更具体。我想在忽略客户端计算机的当前时区(或使用 UTC 时区)的同时将其转换为时间戳。

我有这个代码:

function getTimestampRange(sparams, eparams){

sparams = "2018-11-12", eparams = "2018-11-13"; //sample param values

const start = sparams.split("-");
const end = eparams.split("-");

const startDate = new Date(start[0], start[1] - 1, start[2]);
const endDate = new Date(end[0], end[1] - 1, end[2]);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);

//startDate is 2018-11-12 00:00:00 and endDate is 2018-11-13 23:59:59

const startTS = startDate.getTime() / 1000;
const endTS = endDate.getTime() / 1000;

return [startTS, endTS]
}

一切都很好,但问题是,我正在获取相对于我计算机时区的时间戳。 (格林威治标准时间 + 9)。所以我的纪元是 1970-01-01 的第 9 个小时。这不是我需要的。我需要 GMT+0 UTC 时间戳。

在这种情况下,我会得到 15419484001542121199,分别开始和结束;我应该在哪里得到 15419808001542153599.

Tasukete kudasai

这里有两个选择...

  1. 使用Date.UTC构造UTC时间戳

    const startDate = Date.UTC(start[0], start[1] - 1, start[2]) // a timestamp
    const endDate = Date.UTC(end[0], end[1] - 1, end[2], 23, 59, 59) // a timestamp
    

    注意Date.UTC() 生成以毫秒为单位的时间戳,而不是 Date 实例。由于您可以像上面那样设置小时、分钟和秒,因此您不再需要操作它们。

  2. 使用您现有的符合 ISO 8601 standard 的日期字符串作为 Date 构造函数的唯一参数。

    这得益于this particular nuance...

    Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

    const startDate = new Date(sparams)
    const endDate = new Date(eparams)
    

    Parsing ISO 8601 据说在所有体面的浏览器和 IE v9 中都支持。由于这依赖于特定的 "feature",可能会或可能不会在客户端中实现,因此此方法存在风险因素。


对于您的结束日期,如果进行解析,您可以轻松地将时间和时区部分附加到日期字符串,而不是使用小时、分钟和秒值来操作日期对象。例如

const endDate = new Date(`${eparams}T23:59:59Z`)

或者,使用 Date.prototype.setUTCHours()...

const endDate = new Date(eparams)
endDate.setUTCHours(23, 59, 59)