clean up ago.js, add months as unit

This commit is contained in:
jomo
2014-10-13 02:13:48 +02:00
parent 40d1ca60ef
commit f03d634b88

View File

@@ -1,34 +1,42 @@
$.fn.ago = function(callback) { $.fn.ago = function(callback) {
units = [ units = { // seconds
['minute', 60], minute: 60,
['hour', 3600], //ocd: 100,
['day', 86400], hour: 3600,
['week', 604800], day: 86400,
['year', 31536000] week: 604800,
]; month: 2592000,
year: 31536000
};
this.each(function() { this.each(function() {
// use the callback or parse time from the node's text
ago_date = callback ? callback(this) : new Date($(this).text()); ago_date = callback ? callback(this) : new Date($(this).text());
ago_time = Math.floor((new Date().getTime() - ago_date.getTime())/1000); // get seconds ago
ago_unit = null; ago_time = (new Date().getTime() - ago_date.getTime()) / 1000;
units.forEach(function(time, i) { ago_time = Math.floor(Math.abs(ago_time));
if (Math.abs(ago_time) >= time[1]) {
ago_unit = i; // find unit
var unit_string = null;
var unit_time = null;
for (var unit in units) {
var secs = units[unit];
if (ago_time >= secs) {
unit_string = unit;
unit_time = secs;
} else { } else {
// we found the greatest unit // we found the greatest unit
return; break;
} }
}); }
if (ago_unit !== null) { var ago_str = "just now";
unit = units[ago_unit]; if (unit_time !== null) {
ago_time = Math.abs(Math.floor(ago_time/unit[1])) ago_time = Math.floor(ago_time/unit_time);
ago_str = ago_time.toString() + " " + unit[0] if (ago_time != 1) unit_string += "s"; // plural
if (ago_time != 1) { ago_str = ago_time.toString() + " " + unit_string;
ago_str += "s"; // future or past?
}
ago_str += (ago_time < 0 ? " ahead" : " ago"); ago_str += (ago_time < 0 ? " ahead" : " ago");
} else {
ago_str = "just now";
} }
$(this).text(ago_str); $(this).text(ago_str);