evert revised this gist 2 years ago. Go to revision
1 file changed, 53 insertions
date-diff.ts(file created)
| @@ -0,0 +1,53 @@ | |||
| 1 | + | // https://stackoverflow.com/a/49201872 | |
| 2 | + | const calcDateDifference = ( | |
| 3 | + | start: string | Date, | |
| 4 | + | end: string | Date | |
| 5 | + | ): { year: number; month: number; day: number } => { | |
| 6 | + | // Convert to true dates without time | |
| 7 | + | let startDate = new Date(new Date(start).toISOString().substring(0, 10)); | |
| 8 | + | let endDate = new Date( | |
| 9 | + | (end ? new Date(end) : new Date()).toISOString().substring(0, 10) | |
| 10 | + | ); | |
| 11 | + | ||
| 12 | + | // If start date comes after end, flip them around | |
| 13 | + | if (startDate > endDate) { | |
| 14 | + | const swap = startDate; | |
| 15 | + | startDate = endDate; | |
| 16 | + | endDate = swap; | |
| 17 | + | } | |
| 18 | + | ||
| 19 | + | // Account for leap years | |
| 20 | + | const startYear = startDate.getFullYear(); | |
| 21 | + | const february = | |
| 22 | + | (startYear % 4 === 0 && startYear % 100 !== 0) || startYear % 400 === 0 | |
| 23 | + | ? 29 | |
| 24 | + | : 28; | |
| 25 | + | const daysInMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; | |
| 26 | + | ||
| 27 | + | // Create year and month diffs | |
| 28 | + | let yearDiff = endDate.getFullYear() - startYear; | |
| 29 | + | let monthDiff = endDate.getMonth() - startDate.getMonth(); | |
| 30 | + | if (monthDiff < 0) { | |
| 31 | + | yearDiff--; | |
| 32 | + | monthDiff += 12; | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | // Create day diff while adjusting others | |
| 36 | + | let dayDiff = endDate.getDate() - startDate.getDate(); | |
| 37 | + | if (dayDiff < 0) { | |
| 38 | + | if (monthDiff > 0) { | |
| 39 | + | monthDiff--; | |
| 40 | + | } else { | |
| 41 | + | yearDiff--; | |
| 42 | + | monthDiff = 11; | |
| 43 | + | } | |
| 44 | + | dayDiff += daysInMonth[startDate.getMonth()]; | |
| 45 | + | } | |
| 46 | + | ||
| 47 | + | // Return true differentials | |
| 48 | + | return { | |
| 49 | + | year: yearDiff, | |
| 50 | + | month: monthDiff, | |
| 51 | + | day: dayDiff, | |
| 52 | + | }; | |
| 53 | + | } | |
Newer
Older