Skip to content

Instantly share code, notes, and snippets.

@edfuh
Created September 7, 2011 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edfuh/1199384 to your computer and use it in GitHub Desktop.
Save edfuh/1199384 to your computer and use it in GitHub Desktop.
the time until...
function timeTil(date) {
var t = [
[60 * 60 * 24 * 7 * 4 * 12, 'year'],
[60 * 60 * 24 * 7 * 4, 'month'],
[60 * 60 * 24 * 7, 'week'],
[60 * 60 * 24, 'day'],
[60 * 60, 'hour'],
[60, 'minute'],
[1, 'second']
],
now = +new Date,
then,
diff,
secs;
if (typeof date === 'string') {
then = +new Date(date);
} else if (date.getTime && typeof date.getTime === 'function') {
then = +date;
}
diff = then - now;
secs = diff / 1000;
function getChunk(secs, lastChunk) {
var chunk,
name,
remainder,
til,
chunkTil = lastChunk || '',
i, j;
for (i = 0, j = t.length; i < j; i++) {
chunk = t[i][0];
name = t[i][1];
if (~~(secs / chunk) !== 0) {
remainder = secs % chunk;
break;
}
}
til = Math.round(secs / chunk);
chunkTil += til + ' ' + name + (til > 1 ? 's ' : ' ');
return (remainder > 1) ? getChunk(remainder, chunkTil) : chunkTil;
}
return getChunk(secs);
}
console.log(timeTil('8/27/2011'));
console.log(timeTil(new Date(2012)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment