admin管理员组文章数量:1431449
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?
-
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
4 Answers
Reset to default 4By 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')
本文标签: javascriptMomentjs diff wrong behaviourStack Overflow
版权声明:本文标题:javascript - Moment.js diff wrong behaviour - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745488266a2660482.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论