Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract 2 dates on momentjs

Tags:

momentjs

Hi im currently using momentjs for my dates in my project and im having a bit of trouble when subtracting 2 dates.

Here are my sample dates:

2016-10-08 10:29:23 2016-10-08 11:06:55 

ive tried using the diff and subtract from the guide docs of momentjs but i got nothing.

And what if the date subtracted dates are more than 24 hours?

Thnks in advance.

like image 350
John Geliberte Avatar asked Nov 07 '16 07:11

John Geliberte


People also ask

Why you should not use MomentJS?

However, Moment. js has too many drawbacks compared to modern date and time libraries. Its API is not immutable, it is large and it doesn't support tree shaking. Even the Moment team discourages to use their library in new projects.

Should you still use MomentJS?

Moment. js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size.


1 Answers

You are correct, you can use moment's diff function to subtract two dates (see my example on Plunker):

var date1 = moment('2016-10-08 10:29:23'); var date2 = moment('2016-10-08 11:06:55'); var diff = date2.diff(date1); 

Diff will be equal to 2252000, the number of milliseconds between the two date. See documentation for more details.

You can pass a second argument to diff with the measurement to use (years, months, weeks, days, hours, minutes, and seconds), so if you want to know the number of minutes between the two dates you can write:

var diffInMinutes = date2.diff(date1, 'minutes'); 

And you get 37 minutes.

like image 147
Andrea Avatar answered Sep 19 '22 14:09

Andrea