I am trying with moment.js to know if a date is today, yesterday, 1 week ago, or older (2 weeks ago or more).
I already done that for the first two cases:
var today = moment().startOf('day');
var yesterday = moment().subtract(1, 'days').startOf('day');
if (moment(localTime).isSame(today, 'd')) // today
// do something
if (moment(localTime).isSame(yesterday, 'd')) // yesterday
// do something
Is that correct?
However, how could I check if a date is a week ago, or older (eg. two weeks ago)?
Here's something that can be useful:
Check a JSFiddle demo with more tests, so you can tweak for your exact case, if needed.
The diff function might be helpful for your case and, in general, to check the exact days since a date
Demo
From version 2.14 onwards you can customize the
calendar()
functionThis is designed for 'calendar' type events.
http://momentjs.com/docs/#/displaying/calendar-time/
More precise answer as follows
Moment already contains some logic of this nature
You may want to look at their source code for the
humanize
code https://github.com/moment/moment/blob/ed1fc742b179708d0a987a639979178616309f93/src/lib/duration/humanize.jsand the
fromNow
logichttps://github.com/moment/moment/blob/497f918515ae6ab900f008f19523b1e4ae5e2450/src/lib/moment/from.js
I found this useful to see how they did it.
The way you format the string will depend on your business, and to be honest the built in logic probably won't cut it most of the time. It seems to make sense for the date of a 'post' where 'a few days ago' is ok but I'm tracking packages in the mail and saying 'Your package shipped a few days ago' just isn't good enough.