您如何用Javascript获得今天结束时的Unix时间戳?

时间:2020-07-30 06:10:03

标签: javascript date unix-timestamp

我想获得今天结束的Unix时间戳。

使用此获取今天的开始时间戳,但我想要今天的结束时间戳

var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;

3 个答案:

答案 0 :(得分:0)

  1. 您可以使用.valueOf()方法从日期获取毫秒时间戳,而不是date / 1000
  2. 要结束一天,只需将第二天的日期减少1毫秒

var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// take next day date and reduce for one millisecond
var endOfDay = new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1) - 1);

console.log({
  startOfDay,
  endOfDay,
  startOfDayTimestamp: startOfDay.valueOf(),
  endOfDayTimestamp: endOfDay.valueOf()
})

答案 1 :(得分:0)

首先,获取今天的时间戳:

var now = new Date();

然后从明天开始

var startOfTomorrow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDay() + 1);

现在您已经结束:

var timestampOfEndOfDay = (startOfTomorrow - 1); 

查看结果:

console.log("End of the Day", new Date(timestampOfEndOfDay) );

答案 2 :(得分:0)

864e5是一天中的毫秒数(24 * 60 * 60 * 1000),now % 864e5是日期中的时间部分,以毫秒为单位:

var now = new Date
var startOfDay = new Date(now - now % 864e5)
var endOfDay   = new Date(now - now % 864e5 + 864e5 - 1)

console.log(now)
console.log(startOfDay)
console.log(endOfDay)