How to find exact duration between two Unix dates (in days) using MomentJS?

Viewed 2312

I am trying to find difference between 2 dates, using MomentJS library. However the requirement is to use Unix timestamps as date values.

Currently I have the following code, which returns inaccurate value:

var start = 1536873321; // 13 September 2018
var end = 1537228800 ; // 18 September 2018

var diff = moment.unix(end).diff(moment.unix(start), 'days');
console.log(diff); //4 (expected 5, or 6 if last day is included)

Is there any solution for that, or using plain JavaScript is more suggested to get more precise result?

Please see the fiddle if needed.

3 Answers

Moment is returning 4 days because there are not quite 5 days between those two timestamps.

start = 1536873321; // 13 September 2018 (9:15pm)
end = 1537228800 ; // 18 September 2018 (12:00am)

So the exact time in days between them is 4.114340277777778 days.

Try

start = moment.unix(1536873321);
end = moment.unix(1537228800 );
var diff = Math.ceil(moment.duration(start.diff(end)).asDays());

You don't have to use Unix timestamps. Try this:

var start  = moment("20180913", "YYYYMMDD");
var end = moment("20180918", "YYYYMMDD");

var diff = end.diff(start, "days");
console.log(diff);

That makes the syntax a little cleaner too.

Just call startOf('day') on both so it will calculate the diff between the dates:

var diff = moment.unix(end).startOf('day').diff(moment.unix(start).startOf('day'), 'days');
Related