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.

3 Answers

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest