Reputation: 5383
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 ?
Upvotes: 12
Views: 40861
Reputation: 757
try using string first then number similiar to this
let formattedDate = moment(alarmSchedule).subtract('minutes',20).format();
console.log(formattedDate); // will substract mins from alarmSchedule time
Worked for me!
Upvotes: 0
Reputation: 668
If the time is in this format 2022-04-22T15:10:50+05:00
and you want return in the same format then use
moment(startTime).subtract(10, 'minutes').format()
Upvotes: 1
Reputation: 3516
One line answer:
moment(Date.now()).subtract(60, 'minutes').format()
Upvotes: 4
Reputation: 723
try this it work fine with me
let startTime = moment().format('LT');
let subtract = moment(new Date()).subtract(5,"minutes").format('LT');
startTime 12:03 AM
subtract 11:58 PM
Upvotes: 0
Reputation: 1691
I just faced this issue and solved it.
@rishikarri is right, the moment is getting mutated.
All moments are mutable. If you want a clone of a moment, you can do so implicitly or explicitly.
As an alternative to his answer and for future reference, i propose using clone
as solution.
There are two ways to clone a moment (According to moment docs):
Using moment()
:
var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012
Using .clone()
:
var a = moment([2012]);
var b = a.clone();
a.year(2000);
b.year(); // 2012
All credit goes to the documentation.
Upvotes: 1
Reputation: 4510
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
Upvotes: 5
Reputation: 7490
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
Upvotes: 10