Skip to content

Instantly share code, notes, and snippets.

@THEtheChad
Created October 19, 2011 06:37
Show Gist options
  • Save THEtheChad/1297617 to your computer and use it in GitHub Desktop.
Save THEtheChad/1297617 to your computer and use it in GitHub Desktop.
Function used to calculate the difference between two dates in human readable format
/**!
* @preserve timeDelta
* Copyright 2011 THEtheChad Elliott
* Released under the MIT and GPL licenses.
*/
function timeDelta( start, end, params, only_totals ) {
var delta = {}
, measurements = {
w: 604800000,
d: 86400000,
h: 3600000,
m: 60000,
s: 1000
}
, flags = params || 'wdhms'
;//var
delta.ttl = delta.ms = Math.abs( end.getTime() - start.getTime() );
// do caclulations for each flag
for( i = 0; i < flags.length; i++ ) {
delta[ flags[i] ] = delta.ms / measurements[ flags[i] ];
// unless totals are specified,
// value is broken down into components
if( !only_totals ) {
delta[ flags[i] ] = Math.floor( delta[ flags[i] ] );
delta.ms -= delta[ flags[i] ] * measurements[ flags[i] ];
}
};
return delta;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment