Javascript Friendly Date and Time

I recently had a requirement in javascript to translate a date and time into something more friendly, so that for example 10th January 2014 10:45 becomes “Yesterday 10:45”, or 12:15 today becomes “2 hours ago”. After scanning the various solutions I could find, I came up with the following:

  • < 5 minutes: now
  • < 1 hour: xx minutes ago
  • today: today hh:mm
  • yesterday: yesterday hh:mm
  • < 7 days: day-of-week hh:mm
  • this year: month day
  • default: month day year
function friendlyDate(dateValue) {
    // < 5 mins   : now
    // < 1 hour   : xx minutes ago
    // today      : today hh:mm
    // yesterday  : yesterday hh:mm
    // < 7 days   : day of week hh:mm
    // this year  : month + day
    // default    : month + day + year
    var dateparts = dateValue.toUTCString().split(' '); // Thu May 29 2014 10:09:32 GMT+0000 (GMT)
    var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var now = new Date();

    var diffMsec = now.getTime() - dateValue.getTime();
    var diffMins = Math.round(diffMsec / 60000);

    if (diffMins < 1) {
        return "now";
    } else if (diffMins === 1) {
        return "1 minute ago";
    } else if (diffMins < 60) {
        return diffMins + " minutes ago";
    }

    // ignore time component
    var testDate = new Date(dateValue);
    testDate.setHours(0, 0, 0, 0);
    now.setHours(0, 0, 0, 0);
    var mSecPerDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
    var diffDays = Math.round(Math.abs((now.getTime() - testDate.getTime()) / (mSecPerDay)));

    if (diffDays === 0) {
        return "today " + dateparts[4].substr(0, 5);
    } else if (diffDays === 1) {
        return "yesterday " + dateparts[4].substr(0, 5);
    } else if (diffDays < 7) {
        return weekdays[dateValue.getDay()] + ' ' + dateparts[4].substr(0, 5);
    }

    if (dateValue.getFullYear() === now.getFullYear()) {
        return dateparts[1] + ' ' + dateparts[2];
    }

    return dateparts[1] + ' ' + dateparts[2] + ', ' + dateparts[3];
}

You can try this out on jsfiddle

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s