Last active
June 7, 2016 15:36
-
-
Save diegocasmo/7fbad9ea7ae02ea5f97c to your computer and use it in GitHub Desktop.
Handlebars helper to transform a time stamp in ms to a nicely formatted "31 minutes ago", "1 hour ago" text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Handlebars helper to transform a time stamp ms to a nicely | |
* formatted "31 minutes ago", "1 hour ago" type date. | |
*/ | |
Handlebars.registerHelper('beautify_date', function(options) { | |
var timeAgo = new Date(parseInt(options.fn(this))); | |
if (Object.prototype.toString.call(timeAgo) === '[object Date]') { | |
if (isNaN(timeAgo.getTime())) { | |
return 'Not Valid'; | |
} else { | |
var seconds = Math.floor((new Date() - timeAgo) / 1000), | |
intervals = [ | |
Math.floor(seconds / 31536000), | |
Math.floor(seconds / 2592000), | |
Math.floor(seconds / 86400), | |
Math.floor(seconds / 3600), | |
Math.floor(seconds / 60) | |
], | |
times = [ | |
'year', | |
'month', | |
'day', | |
'hour', | |
'minute' | |
]; | |
var key; | |
for(key in intervals) { | |
if (intervals[key] > 1) | |
return intervals[key] + ' ' + times[key] + 's ago'; | |
else if (intervals[key] === 1) | |
return intervals[key] + ' ' + times[key] + ' ago'; | |
} | |
return Math.floor(seconds) + ' seconds ago'; | |
} | |
} else { | |
return 'Not Valid'; | |
} | |
}); | |
// Usage | |
// {{#beautify_date}} | |
// {{timestamp_ms}} | |
// {{/beautify_date}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment