Created
December 22, 2011 14:23
-
-
Save danielgwood/1510463 to your computer and use it in GitHub Desktop.
Human formatted time between dates (JavaScript)
This file contains hidden or 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
/** | |
* Given two dates (or one date and assume "now" for the second), convert this to | |
* a human-readable string, like "2 months". | |
* | |
* I use this to put "3 months ago" strings into plugins. My use case has the date | |
* coming in as a seconds-only UNIX epoch, so the params are expected at this. | |
* | |
* @param time1 integer Number of seconds since UNIX epoch | |
* @param time2 integer Number of seconds since UNIX epoch | |
* @return string | |
*/ | |
function(time1, time2) { | |
// Check/sanitise vars | |
time1 = Math.max(0, parseInt(time1)); | |
if(typeof time2 == "undefined") { | |
var now = new Date(); | |
time2 = Math.floor(now.getTime() / 1000); | |
} | |
var period = Math.abs(time1 - time2); | |
var timespan = 1; | |
var format = 'seconds'; | |
if (period > 31556926) { | |
// More than one year | |
format = 'years'; | |
timespan = Math.floor(period / 31556926); | |
} | |
else if (period > 2629744) { | |
// More than one month | |
format = 'months'; | |
timespan = Math.floor(period / 2629744); | |
} | |
else if (period > 604800) { | |
// More than one week | |
format = 'weeks'; | |
timespan = Math.floor(period / 604800); | |
} | |
else if (period > 86400) { | |
// More than one day | |
format = 'days'; | |
timespan = Math.floor(period / 86400); | |
} | |
else if (period > 3600) { | |
// More than one hour | |
format = 'hours'; | |
timespan = Math.floor(period / 3600); | |
} | |
else if (period > 60) { | |
// More than one minute | |
format = 'minutes'; | |
timespan = Math.floor(period / 60); | |
} | |
// Remove the s | |
if(timespan == 1) { | |
format = substr(format, 0, -1); | |
} | |
return timespan + ' ' + format; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment