如何获得一天开始和结束的UNIX时间戳?

时间:2020-04-15 12:20:32

标签: javascript momentjs

我正在努力使用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时间戳中正确扣除该偏移量。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解正确,但是如果您尝试获取 UTC一天开始和结束时间的unix时间戳,那就是这样的方式:

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

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

注意:输出格式为数字类型。