Created
August 5, 2011 16:19
-
-
Save peol/1127900 to your computer and use it in GitHub Desktop.
Small, versatile relative time/duration function
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
/** | |
* Copyright(c) 2011 Andrée Hansson | |
* @peolanha | |
* http://github.com/peol | |
* | |
* License: Do whatever you want, some attribution would be nice | |
* | |
* Small, versatile relative time function, options: | |
* asArray: Returns the data in an array, each entry has [0] = number, [1] = string representation | |
* filterValues: Removes all entries with 0 as value | |
* compress: Compresses the string representation to one char and strips the comma between each entry | |
* | |
* Examples at the bottom! | |
*/ | |
function duration(seconds, opts) { | |
opts = opts || { | |
asArray: false, | |
filterValues: true, | |
compress: false | |
}; | |
function subtract(div) { | |
var v = Math.floor( seconds / div ); | |
seconds %= div; | |
return v; | |
} | |
var val = [ | |
[subtract( 31536000 ), ' year'], | |
[subtract( 2628000 ), ' month'], | |
[subtract( 604800 ), ' week'], | |
[subtract( 86400 ), ' day'], | |
[subtract( 3600 ), ' hour'], | |
[subtract( 60 ), ' minute'], | |
[seconds, ' second'] | |
], | |
i = 0, | |
l = val.length, | |
v; | |
for (; i < l; i += 1) { | |
v = val [ i ]; | |
if ( opts.compress ) { | |
// Take first char after space | |
v[ 1 ] = v[ 1 ][ 1 ]; | |
} | |
else { | |
if ( val[ i ][ 0 ] !== 1 ) { | |
// Pluralize | |
val[ i ][ 1 ] += 's'; | |
} | |
} | |
} | |
if ( opts.filterValues ) { | |
val = val.filter(function(i) { | |
return i[ 0 ] > 0; | |
}); | |
} | |
if ( !opts.asArray ) { | |
val = val | |
.map(function(i) { | |
return i.join(''); | |
}) | |
.join(', '); | |
} | |
return opts.compress && !opts.asArray ? | |
val.replace(/,/g,''): | |
val; | |
} | |
/** | |
* Example: | |
* duration(48372); | |
* Output: 13 hours, 26 minutes, 12 seconds | |
* | |
* Example: | |
* duration(9382372, { | |
* compress: true | |
* }); | |
* Output: 3m 2w 3d 8h 12m 52s | |
* | |
* Example: | |
* duration(92372, { | |
* asArray: true | |
* }); | |
* Output: [[1,' day'], [1,' hour'], [39,' minutes'], [32,' seconds']] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment