Skip to content

@RCanine /date-ago.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
YUI module for calculating the time ago in words in English. Updated from the Prototype version and optimized for compressor.
YUI.add('date-ago', function (Y) {
function round(value) {
return Math.round(value);
}
function distanceOfTimeInWords(from_time, to_time, include_s) {
var include_seconds, distance_in_minutes, distance_in_seconds;
include_seconds = include_s || false;
distance_in_minutes = round(Math.abs(to_time - from_time) / 60000);
distance_in_seconds = round(Math.abs(to_time - from_time) / 1000);
if (distance_in_minutes < 2) {
if (include_seconds) {
if (distance_in_seconds < 5) { return 'less than 5 seconds'; }
if (distance_in_seconds < 10) { return 'less than 10 seconds'; }
if (distance_in_seconds < 20) { return 'less than 20 seconds'; }
if (distance_in_seconds < 40) { return 'half a minute'; }
if (distance_in_seconds < 59) { return 'almost a minute'; }
return '1 minute';
}
return (distance_in_minutes === 0) ? 'less than a minute' : '1 minute';
}
if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes'; }
if (distance_in_minutes < 89) { return '1 hour'; }
if (distance_in_minutes < 1439) { return '' + round(distance_in_minutes / 60) + ' hours'; }
if (distance_in_minutes < 2879) { return '1 day'; }
if (distance_in_minutes < 43199) { return round(distance_in_minutes / 1440) + ' days'; }
if (distance_in_minutes < 86399) { return '1 month'; }
if (distance_in_minutes < 525599) { return round(distance_in_minutes / 43200) + ' months'; }
if (distance_in_minutes < 1051199) { return '1 year'; }
return 'over ' + round(distance_in_minutes / 525600) + ' years';
}
function timeAgoInWords(date, includeSeconds) {
var now = new Date();
direction = (now - date > 0) ? ' ago' : ' from now';
return distanceOfTimeInWords(date, now, includeSeconds) + direction;
}
Y.merge(Y.namespace('Date'), {
// JS version of Ruby on Rails' distance_of_time_in_words
distanceOfTimeInWords: distanceOfTimeInWords,
// Returns the time since a date in English
timeAgoInWords: timeAgoInWords
});
}, "3.3.0");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.