判断两个日期是否相差指定年数以内
export const isWithinYearsSpan = (
startDate: string | Date,
endDate: string | Date,
years: number = 1
): boolean => {
const start = new Date(startDate);
const end = new Date(endDate);
const yearDiff = end.getFullYear() - start.getFullYear();
if (yearDiff > years) return false;
if (yearDiff < years) return true;
return (
end.getMonth() < start.getMonth() ||
(end.getMonth() === start.getMonth() && end.getDate() <= start.getDate())
);
};
判断两个日期是否相差指定月数以内
export const isWithinMonthsSpan = (
startDate: string | Date,
endDate: string | Date,
months: number = 1
): boolean => {
const start = new Date(startDate);
const end = new Date(endDate);
const yearDiff = end.getFullYear() - start.getFullYear();
const monthDiff = end.getMonth() - start.getMonth();
const totalMonthDiff = yearDiff * 12 + monthDiff;
if (totalMonthDiff > months) return false;
if (totalMonthDiff < months) return true;
return start.getDate() >= end.getDate();
};