【问题标题】:How can I get UNIX timestamp of the start and and end of the day?如何获取一天的开始和结束的 UNIX 时间戳?
【发布时间】:2020-04-15 12:20:32
【问题描述】:

我正在努力使用 Moment 库获取 UNIX 格式的开始和结束日期值。

我尝试了以下方法:

  console.log(moment().startOf('day').format()); // works correctly - 2020-04-15T00:00:00+02:00

  console.log(moment().startOf('day').format('X')); // not what I need - 1586901600 = 04/14/2020 @ 10:00pm (UTC) (so minus 2h for the timezone)

所以只是为了确保我发送的时间正确:

  console.log(moment.tz("2020-04-15T00:00" , "Europe/Warsaw").unix()); // again not what I need - 1586901600 = 04/14/2020 @ 10:00pm (UTC) (so minus 2h for the timezone)

  console.log(moment().startOf('day').utcOffset(moment().tz(process.env.TIMEZONE).startOf('day').format('x')).format('X')) // again not what I need - 1586901600 = 04/14/2020 @ 10:00pm (UTC) (even with UTC offset)

我读到你实际上不能偏移或时区 UNIX 时间戳,这在任何地方都是一样的。我很好,但是从 UNIX 时间戳中自动扣除 "Europe/Warsaw" 的“优雅方式”是什么。例如,我在配置文件中设置了时区,我希望 JS 根据时区检测偏移量并正确地从 UNIX 时间戳中扣除。

非常感谢任何帮助。

【问题讨论】:

标签: javascript momentjs


【解决方案1】:

我不太确定我是否理解正确,但如果您尝试获取 UTC 中一天的开始和结束的 unix 时间戳,这就是要走的路: p>

const start = moment().utc().startOf('day').unix();
const end = moment().utc().endOf('day').unix();

console.log(start, end);
// 1586908800, 1586995199

注意:输出格式为typeof number。

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2020-02-22
    相关资源
    最近更新 更多