简体   繁体   中英

checking day difference with moment.js

I want to use moment.js to check if a date is today. Does anyone know how to do that?

I tried moment(yesterday_date).diff(moment(), 'days') . This outputs a 1 only if there is a 24 hour difference.

Any ideas? Any help would be appreciated.

You can use startOf('day') and isSame() to do this...

var someDate = moment("2014-07-17 05:00:00");
var isToday = someDate.startOf('day').isSame(moment().startOf('day'));

Fiddle

You could do something like

moment().unix() - moment(yesterday_date).unix();

That should give you the difference in milliseconds. Then you just need to convert to whichever time unit you need.

Edit: Just realised you want to check whether it's today. Then something like this should work:

function isToday(dateString) {
    var today = moment();
    var prevDate = moment(dateString);
    return today.date() == prevDate.date() && today.month() == prevDate.month() && today.year() == prevDate.year();
}

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