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"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top