Skip to content

Instantly share code, notes, and snippets.

@ChrisTM
Created October 31, 2012 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisTM/89b40995409318e3c52c to your computer and use it in GitHub Desktop.
Save ChrisTM/89b40995409318e3c52c to your computer and use it in GitHub Desktop.
duration between two Date objects
/* 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