Skip to content

Instantly share code, notes, and snippets.

@boxnos
Last active November 14, 2019 06:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boxnos/5896114 to your computer and use it in GitHub Desktop.
Save boxnos/5896114 to your computer and use it in GitHub Desktop.
time_ago_in_words in JavaScript
var time_ago_in_words = function(from, to) {
to = to ? to : Date.now();
var minutes = (to - from) / 60000;
var data = [
[0 , 'less than a minute ago'],
[1 , 'a minute ago'],
[2 , function(m) {return m.toFixed() + ' minutes ago';}],
[45 , 'about 1 hour ago'],
[90 , function(m) {return 'about ' + (m / 60).toFixed() + ' hours ago';}],
[1440 , '1 day ago'],
[2880 , function(m) {return (m / 1440).toFixed() + ' days ago';}],
[43200 , 'about 1 month ago'],
[86400 , function(m) {return (m / 43200).toFixed() + ' months ago';}],
[52960 , 'about 1 year ago'],
[1051200, function(m) {return (m / 525960).toFixed() + ' years ago';}],
[Number.MAX_VALUE]
];
function b_search(value, lower, pos, upper) {
if (data[pos][0] <= value && value < data[pos + 1][0])
return data[pos];
else if (value < data[pos][0])
return b_search(value, lower, Math.floor((lower + pos - 1) / 2), pos - 1);
else
return b_search(value, pos + 1, Math.floor((pos + 1 + upper) / 2), upper);
}
var res = b_search(minutes, 0, Math.floor((data.length - 1) / 2), data.length - 1)[1];
return (res instanceof Function) ? res(minutes) : res;
};
@alex-kovshovik
Copy link

I'm getting "Uncaught RangeError: Maximum call stack size exceeded" in Chrome - when accidentally passed in a date in a string. Once converted to a date object - works like a charm! Thank you!

@sunchess
Copy link

sunchess commented Jan 8, 2016

There is a error - 52960 mast be 529600

@msftrncs
Copy link

Line 16 should read [525960 , 'about 1 year ago'],, this is 60 * 24 * 365.25, minutes in a average year.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment