时刻JS:问题减去分钟



这是我部署在 Parse.com CloudCode上的代码:

var now = new Date()
var then = moment(now).subtract(20, "minutes").toDate()
console.log(now)
console.log(then)

为什么now === then

我做错了什么?

我不知道你错了,但对我来说工作正常。没问题。

>var now = new Date()
>var then = moment(now).subtract(20, "minutes").toDate()
>console.log(now)
>console.log(then)
VM145:5 Thu Jan 21 2016 17:26:48 GMT+0100 (CET)
VM145:6 Thu Jan 21 2016 17:06:48 GMT+0100 (CET)
undefined
>now === then
false

我遇到了同样的问题,不得不做类似的事情:

const now = new Date()
const nowCopy = new Date()
const then = moment(nowCopy).subtract(20, "minutes").toDate()
console.log(now)
console.log(then)

我知道这不是最优雅的解决方案,但是当您对其运行操作以获取"then"变量时,您的"now"变量似乎发生了变化

一行答案:

moment(Date.now()).subtract(60, 'minutes').format()

我刚刚面对这个问题并解决了它。

@rishikarri是对的,这一刻正在发生变化。

所有时刻都是可变的。如果你想要一个时刻的克隆,你可以隐式或显式地这样做。

作为他的回答的替代方案和将来的参考,我建议使用clone作为解决方案。

有两种

方法可以克隆时刻(根据时刻文档):

使用moment()

var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012

使用.clone()

var a = moment([2012]);
var b = a.clone();
a.year(2000);
b.year(); // 2012

所有功劳都归于文档。

试试这个,它对我很好用

let startTime = moment().format('LT');
let subtract = moment(new Date()).subtract(5,"minutes").format('LT');

开始时间 12:03 AM

减去 11:58 PM

如果时间是这种格式2022-04-22T15:10:50+05:00并且您希望以相同的格式返回,然后使用

moment(startTime).subtract(10, 'minutes').format()

相关内容

最新更新