简体   繁体   中英

How to get days with moment.js fromNow method

I'd like to get days from a date to now with momentjs.
I've tried with fromNow(). The method return value as string.
And its unit change depends on the length of range.

var m = moment("2014-01-01");  // or whatever start date you have
var today = moment().startOf('day');

var days = Math.round(moment.duration(today - m).asDays());

Or if you prefer, the last line can be simplified:

var days = Math.round((today - m) / 86400000);

Note that even though the start date was specified without a time (which assumes midnight), rounding is still necessary to get a whole number because of potential differences in UTC offset due to daylight saving time.

If you still want to use Moment to get the "In X days" or "X days ago" you can use moment.from(date) instead of moment.fromNow() and just remove all notion of times.

https://momentjs.com/docs/#/displaying/from/

var today = new Date();
today.setHours(0, 0, 0, 0);
dateToCheck.setHours(0, 0, 0, 0)

moment(dateToCheck).from(today);

or a one-liner

moment(dateToCheck.setHours(0, 0, 0, 0)).from(new Date().setHours(0, 0, 0, 0));
const date1 = moment('06-11-2021')
const date2 = moment('06-12-2021')
const diff = date2.diff(date1, 'days')   
console.log("diff: ", diff); // diff: 1

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