Last active
August 29, 2015 13:56
-
-
Save twfarland/9064285 to your computer and use it in GitHub Desktop.
Relative date function
This file contains hidden or 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
// Returns a text description of a past time relative to now, e.g: 1 minute ago, 3 hours ago, 2 years ago. | |
var intervals = [['year', 31556926], ['month', 2629744], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]]; | |
// time is in seconds | |
function textDate (time) { | |
var diff = new Date().valueOf() * 1000 - time, i, v, n; | |
for (i = 0; i < intervals.length; i++) { | |
v = intervals[i]; | |
if (diff > v[1]) { | |
n = Math.floor(diff / v[1]); | |
return n + ' ' + v[0] + ((n === 1) ? '' : 's') + ' ago'; | |
} | |
} | |
return 'Just now'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment