[英]How can I get the correct output with Moment.js and "fromNow"?
For the below program, the run date is 26/10/2017
and the variable deadline=29/10/2017
.对于下面的程序,运行日期是
26/10/2017
并且变量deadline=29/10/2017
。
I am using moment.js:我正在使用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
我的输出是
in 2 days
但实际上我认为正确的答案是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?我认为这是因为
fromNow
也在计算小时数,所以我的问题是,如何重置它,以便获得正确的输出?
You can use .endOf('day')
on your deadline momentjs instance and you'll get 3 days.您可以在截止日期 momentjs 实例上使用
.endOf('day')
,您将获得 3 天。
You can also use a timestamp on top of your date such as 23:59
to get the same functionality.您还可以在日期之上使用时间戳,例如
23:59
以获得相同的功能。
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
.而不是使用
fromNow
您可以使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.