Skip to content

Instantly share code, notes, and snippets.

@ryndel
Last active January 13, 2016 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ryndel/3886864 to your computer and use it in GitHub Desktop.
Save ryndel/3886864 to your computer and use it in GitHub Desktop.
Handlebars.js: prettyDate helper #cc #handlebars
Handlebars.registerHelper("prettyDate", function (time) {
var date = new Date((time || "")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
// exit now if not a number...
if ( isNaN(day_diff)) return;
if ( day_diff < 0 ){
// this is in the future...
return day_diff == 0 && (
diff > -60 && "momentarily" ||
diff > -120 && "in 1 minute" ||
diff > -3600 && "in "+ Math.floor( diff / -60 ) + " minutes" ||
diff > -7200 && "in 1 hour" ||
diff > -86400 && "in "+ Math.floor( diff / -3600 ) + " hours") ||
day_diff == -1 && "Tomorrow" ||
day_diff > -7 && "in "+ (-1*day_diff) + " days" ||
day_diff > -8 && "in a "+ Math.ceil( day_diff / -7 ) + " week" ||
day_diff > -31 && "in "+ Math.ceil( day_diff / -7 ) + " weeks" ||
day_diff > -40 && "in about a month" ||
"in "+ Math.ceil( day_diff / -30 ) + " months";
} else {
// this is in the past...
return day_diff == 0 && (
diff < 60 && "just now" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 8 && Math.ceil( day_diff / 7 ) + " week ago" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
day_diff < 40 && Math.ceil( day_diff / 30 ) + " month ago" ||
Math.ceil( day_diff / 30 ) + " months ago";
}
});
@tracend
Copy link

tracend commented May 17, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment