Skip to content

Instantly share code, notes, and snippets.

@sevab
Last active January 24, 2016 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sevab/88da8a8a531bf832cd80 to your computer and use it in GitHub Desktop.
Save sevab/88da8a8a531bf832cd80 to your computer and use it in GitHub Desktop.
Express past and future dates in relative words in JavaScript
/**
* A lighter version based on https://github.com/jherdman/javascript-relative-time-helpers
*
* Takes a date either in the future or the past and returns distance of time in words from that date up to now
*
* Examples:
*
* - current date:
* toRelativeTime(new Date())
* > 'Just now'
*
* - past date
* toRelativeTime(new Date('Tue, 21 Jan 2016'))
* > '3 days ago'
*
* - future date
* toRelativeTime(new Date('Tue, 29 Jan 2016 02:08:09 UTC +00:00'))
* > 'in 5 days'
*
*/
function toRelativeTime(date) {
var CONVERSIONS = {
millisecond: 1, // ms -> ms
second: 1000, // ms -> sec
minute: 60, // sec -> min
hour: 60, // min -> hour
day: 24, // hour -> day
month: 30, // day -> month (roughly)
year: 12 // month -> year
};
var now = new Date();
var delta = now - date;
var future = (delta <= 0);
delta = Math.abs(delta);
// default threshold is 0
if (delta <= 0) { return 'Just now'; }
var units = null;
for (var key in CONVERSIONS) {
if (delta < CONVERSIONS[key])
break;
units = key; // keeps track of the selected key over the iteration
delta = delta / CONVERSIONS[key];
}
delta = Math.round(delta);
// pluralize a unit when the difference is greater than 1.
if(delta > 1) units += "s";
return (future ? ["in", delta, units] : [delta, units, "ago"]).join(" ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment