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

javascript - Moment.js diff wrong behaviour - Stack Overflow

programmeradmin1浏览0评论

I have a date and I want to substract today of this date. This is my example:

date.format('YYYY-MM-DD')
"2018-04-07"
moment().format('YYYY-MM-DD')
"2018-04-06"
date.diff(moment(), 'days')
0

The diff call returns 0 instead of 1. What is wrong here?

I have a date and I want to substract today of this date. This is my example:

date.format('YYYY-MM-DD')
"2018-04-07"
moment().format('YYYY-MM-DD')
"2018-04-06"
date.diff(moment(), 'days')
0

The diff call returns 0 instead of 1. What is wrong here?

Share Improve this question asked Apr 6, 2018 at 8:29 Frank RothFrank Roth 6,3393 gold badges27 silver badges33 bronze badges 3
  • Can you show what is date? – VincenzoC Commented Apr 6, 2018 at 8:32
  • What is date? How is it created? – RobG Commented Apr 6, 2018 at 9:20
  • date = new Date(...); – Frank Roth Commented Dec 19, 2019 at 9:08
Add a ment  | 

4 Answers 4

Reset to default 4

By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned a number rounded to the nearest integer, not a truncated number.

To see the full value, pass true as the third parameter:

 now.diff(date, 'days', true)

If you want to pare just dates, then use:

var now = moment().startOf('day');

which will set the time to 00:00:00 in the local time zone. And pare with date

Use fromNow() function to understand why you are getting 0 instead of 1. It is very straight-forward.

Do like this :

moment(date).fromNow();

It will give you number of days passed if time is greater than 24 hours otherwise it will give to time in hours. e.g. 2 hours ago, 23 hours etc.

Below is example:

console.log(moment("2018-04-06", "YYYY-MM-DD").fromNow());
<script src="//cdnjs.cloudflare./ajax/libs/moment.js/2.17.1/moment.min.js"></script>

So you can see it is returning 18 hours ago (as of now) which is less than 24hours i.e. 1 day.

I would suggest to use fromNow instead of diff to get exact difference.

Hope now it makes clear to you.

moment() returns a full moment including time, so it's doing a diff from today, including time, to midnight of the 7th of April, which isn't a full day.

I was also facing the same issue. So after a few research on StackOverflow and moment.js documentation I came up with this solution. Works perfectly for me.

const date1 = "2021-05-12T06:30:00.000Z"
const date2 = "2021-05-18T06:30:00.000Z"

const day1 = moment((moment(date1).format("YYYY-MM-DD")).split("-"))
const day2 = moment((moment(date2).format("YYYY-MM-DD")).split("-"))


const diff = day2.diff(day1,'days')
发布评论

评论列表(0)

  1. 暂无评论