I'd like to display some dates as relative to the current date in a human-friendly format.
Examples of human-friendly relative dates:
Basically faithfully preserving the highest order of magnitude (and by preference, only shifting up units when passing 2 of those units - 5 weeks instead of 1 month).
Though I could live with a library that had less control and even more friendly dates like:
Any popular libraries for this?
Best overall: date-fns date-fns offers great documentation, functional architecture, and utilities that handle almost any task you can think of. If dates are a critical concern for your JavaScript application, use date-fns. Each feature has clear documentation written in ESM (ES Modules) for the browser.
now() The static Date. now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
Since I wrote this answer, a well known library available is moment.js.
There are libraries available, but it is trivial to implement it yourself. Just use a handful of conditions.
Assume date
is an instantiated Date
object for the time you want to make a comparison against.
// Make a fuzzy time var delta = Math.round((+new Date - date) / 1000); var minute = 60, hour = minute * 60, day = hour * 24, week = day * 7; var fuzzy; if (delta < 30) { fuzzy = 'just then.'; } else if (delta < minute) { fuzzy = delta + ' seconds ago.'; } else if (delta < 2 * minute) { fuzzy = 'a minute ago.' } else if (delta < hour) { fuzzy = Math.floor(delta / minute) + ' minutes ago.'; } else if (Math.floor(delta / hour) == 1) { fuzzy = '1 hour ago.' } else if (delta < day) { fuzzy = Math.floor(delta / hour) + ' hours ago.'; } else if (delta < day * 2) { fuzzy = 'yesterday'; }
You would need to adapt this to handle future dates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With