Created
July 21, 2017 16:45
-
-
Save garystorey/9d2c8a280e5bffb342cbaac5c44a938c to your computer and use it in GitHub Desktop.
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
function diffDates(startDate, endDate) { | |
var t, multiplier = 1; | |
if (startDate > endDate) { | |
t = startDate; | |
startDate = endDate; | |
endDate = t; | |
multiplier = -1; | |
} | |
var millisTotal = endDate - startDate, | |
millis = millisTotal % 1000, | |
secsTotal = Math.floor(millisTotal / 1000), | |
secs = secsTotal % 60, | |
minsTotal = Math.floor(secsTotal / 60), | |
mins = minsTotal % 60, | |
hoursTotal = Math.floor(minsTotal / 60), | |
hours = hoursTotal % 24, | |
daysTotal = Math.floor(hoursTotal / 24), | |
weekDays = daysTotal % 7, | |
weeksTotal = Math.floor(daysTotal / 7); | |
var startDay = startDate.getDate(), endDay = endDate.getDate(), | |
startMonth = startDate.getMonth(), endMonth = endDate.getMonth(), | |
startYear = startDate.getFullYear(), endYear = endDate.getFullYear(); | |
var yearsTotal = endYear - startYear; | |
t = new Date(+startDate); | |
t.setFullYear(startYear + yearsTotal); | |
if (t > endDate) { | |
yearsTotal--; | |
} | |
var monthsTotal = yearsTotal * 12 + (startMonth > endMonth ? (12 - startMonth + endMonth) : (endMonth - startMonth)); | |
t = new Date(+startDate); | |
t.setMonth(t.getMonth() + monthsTotal); | |
if (t > endDate) { | |
monthsTotal--; | |
} | |
else if(startMonth == endMonth && t.getFullYear() < endYear) { | |
monthsTotal += 11; | |
} | |
var months = monthsTotal % 12; | |
t = new Date(endYear, endMonth - (endDay < startDay ? 1 : 0), startDay, startDate.getHours(), startDate.getMinutes(), startDate.getSeconds(), startDate.getMilliseconds()); | |
if (t.getDate() != startDay) { | |
t = new Date(t - t.getDate() * 24 * 60 * 60 * 1000); | |
} | |
var monthDays = Math.floor((endDate - t) / (24 * 60 * 60 * 1000)); | |
return { | |
millisTotal: multiplier * millisTotal, | |
millis: multiplier * millis, | |
secsTotal: multiplier * secsTotal, | |
secs: multiplier * secs, | |
minsTotal: multiplier * minsTotal, | |
mins: multiplier * mins, | |
hoursTotal: multiplier * hoursTotal, | |
hours: multiplier * hours, | |
daysTotal: multiplier * daysTotal, | |
weekDays: multiplier * weekDays, | |
yearsTotal: multiplier * yearsTotal, | |
monthsTotal: multiplier * monthsTotal, | |
monthDays: multiplier * monthDays, | |
months: multiplier * months, | |
weeksTotal: multiplier * weeksTotal | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment