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...
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