How to subtract and add dates with javascript?

Asked

Viewed 69 times

0

I have two dates and I need to make a delta of these dates to add in the following ones. See below:

data1 = 2020-08-14T10:02 data2 = 2020-08-14T10:07

The code below brings the difference of these dates:

var a = moment('2020-08-14T10:02');
var b = moment('2020-08-14T10:07');

console.log(b.diff(a, 'minutes'))
console.log(b.diff(a, 'hours'))
console.log(b.diff(a, 'days'))
console.log(b.diff(a, 'weeks'))

//5
//0
//0
//0

Now I want the date3 to be "2020-08-14T10:07" and add the 5 minutes difference in the date4, can help me?

1 answer

0

As the object Moment implements the method valueOf to return time in milliseconds, you can just subtract the objects to capture the difference.

Then use the method add to add the difference to your date. However the method add does not generate a new object, it modifies the object that invokes the method, if you want to generate an object Moment separate, clone the previous object with the method clone before adding the difference:

var a = moment('2020-08-14T10:02');
var b = moment('2020-08-14T10:07');

var diff = b - a;
var c = b.clone().add(diff, 'millisecond');
var d = c.clone().add(diff); // informar que a diferença é em milissegundos é opcional

// isso também é possível graças ao método valueOf, 
// mas se você gerar uma nova data a partir dos milissegundos, 
// você irá perder o fuso horário dessa data
var e = moment(d + diff);

console.log('a:', a);
console.log('b:', b);
console.log('c:', c);
console.log('d:', d);
console.log('e:', e);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

  • Very well explained and this seems to be the way, but strange that for me the var d is picking the same date of c and is not adding the difference.

  • You generated d from a clone of c?

  • Yes, it looked like this: var d = c.clone(). add(diff);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.