我的需求是当前时间戳+1天,百度得到的答案:
// 当前时间戳(秒级)
let timestamp = Date.parse(new Date());
console.log('[今天时间戳:]',timestamp)
// + 1年
let targerTime = (timestamp/1000 + 86400)*1000;
console.log('[加1天的时间戳:]',targerTime);
有个地方不是很理解,为什么要先除于1000呢,有什么含义吗?直接+86400秒为什么不行?
+86400
是肯定不行的,你需要+86400 * 1000
这里面主要就这么几个知识 点:
JS 的时间戳是毫秒,
86400
是秒,相加需要乘以1000
:你看看上面这样是不是多此一举
Date.parse()
得到的结果,永远都会是以000
结尾,即没有毫秒精度的时间戳:Date.prototype.toString()
方法默认格式会没有毫秒精度,可以试试下面这样:得到的结果就有可能是
1634608265224
这样的值了,这个时候,你才需要使用(timestamp/1000 + 86400)*1000
,但也不是这样,而是:(Math.round(timestamp/1000) + 86400)*1000
,把timestamp / 1000
之后,Math.round
去掉后面的小数部分,得到一个纯净的时间戳