Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MomentJS : Issue subtracting minutes

This is my code that is deployed on Parse.com CloudCode :

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

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

Why does now === then ?

What am I doing wrong ?

like image 577
Cherif Avatar asked Jan 21 '16 16:01

Cherif


Video Answer


3 Answers

One line answer:

moment(Date.now()).subtract(60, 'minutes').format()
like image 110
Ibad Shaikh Avatar answered Oct 04 '22 09:10

Ibad Shaikh


I don't know you were wrong, but for me works properly. No issues.

>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
like image 10
Serginho Avatar answered Oct 16 '22 18:10

Serginho


I had the same issue and had to do something similar to this:

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

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

I know it's not the most elegant solution but it appears your "now" variable is getting mutated when you run an operation on it to get your "then" variable

like image 5
rishikarri Avatar answered Oct 16 '22 20:10

rishikarri