snippets/date-diff.ts

53 lines
1.4 KiB
TypeScript

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