如何在NodeJs或javascript中添加24小时当前unix时间戳

How to add 24hr in current unix timestamp in NodeJs or in javascript?

本文关键字:24小时 unix 时间戳 添加 NodeJs javascript      更新时间:2023-09-26

我想在nodejs或javascript中添加24小时的unix时间戳。我还想知道是否有任何直接的函数或属性在日期DOM对象。我在PHP中找到了相关的函数。此代码将在当前unix时间戳中添加24小时后返回新的unix时间。

$currentUnixTime=time();
$newUnixTime=strtotime('+1 day', $currentUnixTime);
return newUnixTime;
var myDate = new Date();
myDate.setHours(myDate.getHours()+24);
return myDate;

如果你特别想添加一天,你应该使用momentjs库,它可用于frontent和nodejs。

var now = new Date()
var tomorrow = moment(now).add(1, 'day');

这比添加24小时更健壮,因为它考虑了DST的变化。由于这个原因,在大多数情况下,你应该避免在JS中直接操作Date

http://momentjs.com/docs//操作/添加/

月份和年份的特殊考虑

如果原日期的第几天大于最后一个月的天数,该月的日期将更改为最后一个月的最后一天

moment([2010, 0, 31]);                  // January 31
moment([2010, 0, 31]).add(1, 'months'); // February 28

在添加时间时还需要记住一些特殊的注意事项这跨越了日光节约时间。如果你要加年数,月、周或日,原始小时将始终与添加的小时匹配小时。

var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US m.hours(); // 5 
m.add(1, 'days').hours(); // 5

如果要添加小时、分钟、秒或毫秒,则假设你想要精确到小时,结果会是

var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US m.hours(); // 5
m.add(24, 'hours').hours(); // 6