MomentJS:减去分钟的问题

时间:2016-01-21 16:25:10

标签: javascript date momentjs

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

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

console.log(now)
console.log(then)

为什么now === then

我做错了什么?

5 个答案:

答案 0 :(得分:6)

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

>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

答案 1 :(得分:3)

我有同样的问题,不得不做类似的事情:

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

console.log(now)
console.log(then)

我知道这不是最优雅的解决方案,但是当你对它运行一个操作以获得你的“当时”变量时,你的“现在”变量似乎会发生变异

答案 2 :(得分:0)

我只是面对这个问题并解决了。

@rishikarri是正确的,此刻正在变异。

所有时刻都是可变的。如果您想复制一下,可以隐式或显式地进行。

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

克隆时刻有两种方法(根据moment docs):

使用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

所有功劳归于文档。

答案 3 :(得分:0)

试试这个它对我很好

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

开始时间 12:03 AM

减去晚上 11:58

答案 4 :(得分:0)

一行回答:

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