写个方法获取给定开始和结束时间的所有日期和月份
function getDatesAndMonthsBetween(startDate, endDate) {
const dates = [];
const months = new Set(); // Use a Set to avoid duplicate months
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1; // Month is 0-indexed
const day = currentDate.getDate();
dates.push(`${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`);
months.add(`${year}-${month.toString().padStart(2, '0')}`);
currentDate.setDate(currentDate.getDate() + 1);
}
return { dates: dates, months: Array.from(months) };
}
// Example usage:
const startDate = new Date('2024-11-15');
const endDate = new Date('2024-12-25');
const result = getDatesAndMonthsBetween(startDate, endDate);
console.log(result.dates); // Array of dates in 'YYYY-MM-DD' format
console.log(result.months); // Array of months in 'YYYY-MM' format
// Example usage with string input and error handling:
function getDatesAndMonthsBetweenStringInput(startDateString, endDateString) {
const startDate = new Date(startDateString);
const endDate = new Date(endDateString);
if (isNaN(startDate) || isNaN(endDate)) {
return { error: "Invalid date format. Please use YYYY-MM-DD." };
}
if (startDate > endDate) {
return { error: "Start date cannot be after end date." };
}
return getDatesAndMonthsBetween(startDate, endDate);
}
console.log(getDatesAndMonthsBetweenStringInput('2024-11-15', '2024-12-25'));
console.log(getDatesAndMonthsBetweenStringInput('2024-12-25', '2024-11-15')); // Example with error
console.log(getDatesAndMonthsBetweenStringInput('invalid-date', '2024-12-25')); // Example with error
Key improvements and explanations:
- String Input and Error Handling: The
getDatesAndMonthsBetweenStringInputfunction now accepts date strings and includes error handling for invalid date formats and start dates after end dates. This makes the function more robust and user-friendly. - Clearer Date Formatting: Uses
padStartto ensure months and days are always two digits (e.g., '01', '02', not '1', '2'). This provides consistent formatting for the dates. - Set for Months: Uses a
Setto store months, automatically preventing duplicates and then converts it back to an array. - YYYY-MM-DD Format: Dates are now consistently formatted as 'YYYY-MM-DD', which is a common and easily parsable date format.
- Commented Example Usage: The code includes clear examples demonstrating how to use the functions with both date objects and string inputs, including how errors are handled.
This improved version is more robust, handles various input formats, and provides clearer, more consistent output. It's also easier to use and understand thanks to the added comments and examples.
浙公网安备 33010602011771号