-
-
Save ByteDecoder/a56a7369e73389f06d8996669d6a7257 to your computer and use it in GitHub Desktop.
"Distance of Time in Words" in Vanilla JavaScript.
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
var TimeAgo = (function() { | |
var self = {}; | |
// Public Methods | |
self.locales = { | |
prefix: '', | |
sufix: 'ago', | |
seconds: 'less than a minute', | |
minute: 'about a minute', | |
minutes: '%d minutes', | |
hour: 'about an hour', | |
hours: 'about %d hours', | |
day: 'a day', | |
days: '%d days', | |
month: 'about a month', | |
months: '%d months', | |
year: 'about a year', | |
years: '%d years' | |
}; | |
self.inWords = function(timeAgo) { | |
var seconds = Math.floor((new Date() - parseInt(timeAgo)) / 1000), | |
separator = this.locales.separator || ' ', | |
words = this.locales.prefix + separator, | |
interval = 0, | |
intervals = { | |
year: seconds / 31536000, | |
month: seconds / 2592000, | |
day: seconds / 86400, | |
hour: seconds / 3600, | |
minute: seconds / 60 | |
}; | |
var distance = this.locales.seconds; | |
for (var key in intervals) { | |
interval = Math.floor(intervals[key]); | |
if (interval > 1) { | |
distance = this.locales[key + 's']; | |
break; | |
} else if (interval === 1) { | |
distance = this.locales[key]; | |
break; | |
} | |
} | |
distance = distance.replace(/%d/i, interval); | |
words += distance + separator + this.locales.sufix; | |
return words.trim(); | |
}; | |
return self; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment