Created
October 31, 2012 02:16
-
-
Save ChrisTM/89b40995409318e3c52c to your computer and use it in GitHub Desktop.
duration between two Date objects
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
/* Return a delta object whose days, hours, minutes, seconds property add up to | |
* the amount of time between timeA and timeB. Assumes A happens before B. */ | |
var duration = function (timeA, timeB) { | |
var msPer = // milliseconds per various times | |
{ second: 1000 | |
, minute: 1000 * 60 | |
, hour: 1000 * 60 * 60 | |
, day: 1000 * 60 * 60 * 24 | |
}; | |
var delta = {}; | |
// number of milliseconds still unaccounted for by the delta object | |
var ms = timeB - timeA; | |
// if `ms` is negative, we make it positive so that the modulus/division | |
// logic still works correctly. `one` is used again when saving the deltas so | |
// that they are correctly saved as negatives if `ms` was originally | |
// negative. | |
var one = (ms < 0) ? -1 : 1; | |
ms *= one; | |
// calculate how many total days, hours, minutes, seconds add up to the given | |
// ms delta by subtracting the biggest amount of days, hours, minute, then | |
// seconds possible from the reamining milliseconds. | |
_.each(['day', 'hour', 'minute', 'second'], | |
function (unit) { | |
var factor = msPer[unit]; | |
// the 's' is for pluralizing the attributes on the delta object | |
delta[unit + 's'] = Math.floor(ms / factor) * one; | |
ms = ms % factor; | |
} | |
); | |
return delta; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment