From 5b56273ffa0b48bf163de3fbd1f68bb69bbad4c1 Mon Sep 17 00:00:00 2001 From: Evert Prants Date: Fri, 21 Jul 2023 12:04:49 +0000 Subject: [PATCH] Add date difference calculator --- date-diff.ts | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 date-diff.ts diff --git a/date-diff.ts b/date-diff.ts new file mode 100644 index 0000000..9aa7db7 --- /dev/null +++ b/date-diff.ts @@ -0,0 +1,53 @@ +// https://stackoverflow.com/a/49201872 +const calcDateDifference = ( + start: string | Date, + end: string | Date +): { year: number; month: number; day: number } => { + // Convert to true dates without time + let startDate = new Date(new Date(start).toISOString().substring(0, 10)); + let endDate = new Date( + (end ? new Date(end) : new Date()).toISOString().substring(0, 10) + ); + + // If start date comes after end, flip them around + if (startDate > endDate) { + const swap = startDate; + startDate = endDate; + endDate = swap; + } + + // Account for leap years + const startYear = startDate.getFullYear(); + const february = + (startYear % 4 === 0 && startYear % 100 !== 0) || startYear % 400 === 0 + ? 29 + : 28; + const daysInMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + // Create year and month diffs + let yearDiff = endDate.getFullYear() - startYear; + let monthDiff = endDate.getMonth() - startDate.getMonth(); + if (monthDiff < 0) { + yearDiff--; + monthDiff += 12; + } + + // Create day diff while adjusting others + let dayDiff = endDate.getDate() - startDate.getDate(); + if (dayDiff < 0) { + if (monthDiff > 0) { + monthDiff--; + } else { + yearDiff--; + monthDiff = 11; + } + dayDiff += daysInMonth[startDate.getMonth()]; + } + + // Return true differentials + return { + year: yearDiff, + month: monthDiff, + day: dayDiff, + }; +} \ No newline at end of file