rampion rampion - 4 months ago 40
Javascript Question

Javascript library for human-friendly relative date formatting

I'd like to display some dates as relative to the current date in a human-friendly format.

Examples of human-friendly relative dates:


  • 10 seconds ago

  • 20 minutes from now

  • 1 day ago

  • 5 weeks ago

  • 2 months ago



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:


  • yesterday

  • tomorrow

  • last week

  • a few minutes ago

  • in a couple hours



Any popular libraries for this?

Answer

Since I wrote this answer, the best 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.