Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js show diff between 2 dates

Tags:

momentjs

I use moment(d, "YYYYMMDD").fromNow(); to get diff between date now and some date, but I would like to get without string "a few days ago".

Instead, I would like to get "7d" (7m, 1s, etc).

How can I do this?

like image 707
Vahe Akhsakhalyan Avatar asked Feb 12 '17 10:02

Vahe Akhsakhalyan


People also ask

How do you find the difference between two dates in a moment?

Date difference with Moment objects You can also create Moment objects and then calculate the difference: var admission = moment('{date1}', 'DD-MM-YYYY'); var discharge = moment('{date2}', 'DD-MM-YYYY'); discharge.

How do you subtract two times using a moment?

add(1, 'day'); // calculate the duration var d = moment. duration(end. diff(start)); // subtract the lunch break d. subtract(30, 'minutes'); // format a string result var s = moment.


2 Answers

If you want just to get the difference between two dates instead of a relative string just use the diff function.

var date  = moment("20170101", "YYYYMMDD"); var date7 = moment("20170108", "YYYYMMDD"); var mins7 = moment("20170101 00:07", "YYYYMMDD HH:mm"); var secs1 = moment("20170101 00:00:01", "YYYYMMDD HH:mm:ss");  console.log(date7.diff(date, "days")    + "d"); // "7d" console.log(mins7.diff(date, "minutes") + "m"); // "7m" console.log(secs1.diff(date, "seconds") + "s"); // "1s" 
like image 103
codersl Avatar answered Sep 25 '22 13:09

codersl


Moment.diff does exactly that.

var a = moment([2007, 0, 29]); var b = moment([2007, 0, 28]); a.diff(b) // 86400000 

You can specify a unit:

var a = moment([2007, 0, 29]); var b = moment([2007, 0, 28]); a.diff(b, 'days') // 1 
like image 27
Brother Woodrow Avatar answered Sep 21 '22 13:09

Brother Woodrow