简体   繁体   中英

Relative time with moment.js but with one day granularity

I am using moment.js to display dates in a readable format. What I want is to display them relatively to current time (1 day ago, 2 weeks ago and so on).

In documentation, I found that I have to use fromnow() , but I do not care about minutes, seconds and hours. So instead of 6 minutes ago or 2 hours ago I want to show today. Further looking into documentation has not brought me anywhere. Is there a way to do this?

Check if it's within 22 hours, and use "today" if that's the case - otherwise use from():

moment() < moment('2014-05-14 13:00:00').add('hours', 22) ? 'today' : moment('2014-05-14 13:00:00').from(moment());
"a day ago"

moment() < moment('2014-05-15 13:00:00').add('hours', 22) ? 'today' : moment('2014-05-15 13:00:00').from(moment());
"today"

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