最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Sep 13, 2018 at 21:50 egurbegurb 1,2162 gold badges16 silver badges43 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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');
发布评论

评论列表(0)

  1. 暂无评论