MomentJS : Issue subtracting minutes
Asked Answered
H

7

12

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 ?

Humes answered 21/1, 2016 at 16:25 Comment(0)
T
10

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
Taradiddle answered 21/1, 2016 at 16:28 Comment(2)
I've tried again, checked everything, still doesn't work for me :(Humes
What browser are you using?Taradiddle
T
5

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

Tilford answered 5/10, 2017 at 21:12 Comment(0)
H
4

One line answer:

moment(Date.now()).subtract(60, 'minutes').format()
Holmic answered 31/7, 2021 at 21:43 Comment(0)
O
1

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.

Outmaneuver answered 30/11, 2020 at 15:10 Comment(0)
K
1

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()

Kilah answered 22/4, 2022 at 10:30 Comment(0)
C
0

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

Cartercarteret answered 20/12, 2020 at 21:2 Comment(0)
Q
0

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!

Quinones answered 17/10, 2023 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.