For the below program, the run date is 26/10/2017
and the variable deadline=29/10/2017
.
I am using moment.js:
var deadline = '29/10/2017' var days = moment(deadline, "DD/MM/YYYY").fromNow(); console.log(days)
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
My output is in 2 days
but actually I think the right answer is in 3 days
I think it is because fromNow
is also calulating with the hours, so my question is, how can I reset this, so that I get the correct output?
You can use .endOf('day')
on your deadline momentjs instance and you'll get 3 days.
You can also use a timestamp on top of your date such as 23:59
to get the same functionality.
var deadline = '29/10/2017' var days = moment(deadline, "DD/MM/YYYY").endOf('day').fromNow(); // Change the time to 23:59:59 ^^^^^^^^^^^^^ console.log(days)
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
Rather than using fromNow
you can use from
. With this, you can reset today's date to midnight and compare it against that instead:
var deadline = '29/10/2017', now = new Date().setHours(0,0,0,0), days = moment(deadline, "DD/MM/YYYY").from(now); console.log(days)
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.