简体   繁体   中英

Moment js Time Ago calculate wrong date

maybe a simple question but i don't get it.

var date = new Date();
test = date.toISOString();
alert(moment(test, "YYYYMMDD").fromNow());

Will return "16 hours", but why?

Demo: https://jsfiddle.net/5jacaxbf/

Because you are using moment(String, String) , instead of moment(String) ( toISOString() output is obviously in ISO 8601 format) or moment(Date) .

So moment(test, "YYYYMMDD") will be the start of the day instead of the current time.

As the Default section states:

You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.

 var date = new Date(); test = date.toISOString(); var m1 = moment(test, "YYYYMMDD") console.log(m1.format()); console.log(m1.fromNow()); var m2 = moment(test) console.log(m2.format()); console.log(m2.fromNow()); var m3 = moment(date) console.log(m3.format()); console.log(m3.fromNow()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM