gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:58:00 26 4
gpt4 key购买 nike

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

基本上我有一个格式为 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

久达斋

最佳答案

这里有两个选择...

  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从 v9 开始,所有体面的浏览器和 IE 都应该支持。由于这依赖于特定的“功能”,可能会或可能不会在客户端中实现,因此此方法存在风险因素。


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

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

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

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

关于javascript - 使用 UTC/GMT+0 作为忽略本地时区纪元的纪元从特定日期获取当前时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53273046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com