最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get days with moment.js fromNow method - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Oct 7, 2014 at 5:15 Matt Johnson-Pint 242k75 gold badges462 silver badges607 bronze badges asked Oct 5, 2014 at 9:37 akazahakazah 3911 gold badge4 silver badges11 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12
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
发布评论

评论列表(0)

  1. 暂无评论