根据输入日期计算从当前季度末开始的连续8个季度的季度末日期。
import { addMonths, differenceInDays, endOfMonth } from "date-fns";
// Get the last day of the quarter for a given date
const getQuarterEndDate = (date: Date): Date => {
const year = date.getFullYear();
const month = date.getMonth();
const quarterMonth = Math.floor(month / 3) * 3 + 2; // Calculate the last month of the current quarter
return endOfMonth(new Date(year, quarterMonth, 1));
};
// Calculate the quarter end dates starting from the current quarter end for a specified number of quarters
const getNextQuarterEndDates = (startDate: Date, count: number): Date[] => {
const nextQuarterEndDates: Date[] = [];
let currentQuarterEnd = getQuarterEndDate(startDate);
for (let i = 0; i < count; i++) {
if (differenceInDays(startDate, currentQuarterEnd) === 0) {
count++; // If the start date and current quarter end date are the same, increment the count to include one more quarter
} else {
nextQuarterEndDates.push(currentQuarterEnd); // Add the current quarter end date to the result array
}
const nextQuarterStart = addMonths(currentQuarterEnd, 1); // Calculate the start date of the next quarter
currentQuarterEnd = getQuarterEndDate(nextQuarterStart); // Calculate the end date of the next quarter and update it as the current quarter end date
}
return nextQuarterEndDates;
};
// Example usage
const inputDate = new Date("2023-07-05");
const nextQuarterEndDates = getNextQuarterEndDates(inputDate, 8);
const formattedDates = nextQuarterEndDates.map((date) =>
date.toISOString().substring(0, 10)
);
console.log(formattedDates);
新手练习,请大神们指教。