Created
May 5, 2011 16:54
-
-
Save chrisdone/957412 to your computer and use it in GitHub Desktop.
time_as_relative
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
function time_as_relative(t1,t2,fix){ | |
var diff = t1 - t2; | |
var minute = 60, hour = minute * 60, day = hour * 24, | |
week = day * 7, month = day * 30, year = month * 12; | |
return in_range( | |
[0,'just now'], | |
[5,'% seconds',1], | |
[minute,'a minute'], | |
[minute*2,'% minutes',minute], | |
[minute*30,'half an hour'], | |
[minute*31,'% minutes',minute], | |
[hour,'an hour'], | |
[hour*2,'% hours',hour], | |
[hour*3,'a few hours'], | |
[hour*4,'% hours',hour], | |
[day,'a day'], | |
[day*2,'% days',day], | |
[week,'a week'], | |
[week*2,'% weeks',week], | |
[month,'a month'], | |
[month*2,'% months',month], | |
[year,'a year'], | |
[year*2,'% years',year] | |
); | |
function in_range() { | |
var span = Math.abs(diff/1000); | |
for (var i = arguments.length-1; i >= 0; i--) { | |
var range = arguments[i]; | |
if (span >= range[0]) { | |
return ( | |
(fix&& diff>0?'in ':'') + | |
(range[1].match(/%/)? | |
range[1].replace(/%/g,Math.round(span/(range[2]? range[2] : 1))) | |
: range[1]) + | |
(fix&& diff<0?' ago':'') | |
); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment