Add date difference calculator

This commit is contained in:
Evert Prants 2023-07-21 12:04:49 +00:00
parent 4b320ff7cf
commit 5b56273ffa
1 changed files with 53 additions and 0 deletions

53
date-diff.ts Normal file
View File

@ -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,
};
}