/* 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; };