JavaScript
// daysInMonths.js
/**
* Calculates the number of days in each month for a given year.
* Handles leap years correctly for February.
*
* @param {number} [year=new Date().getFullYear()] - The year for which to calculate the days.
* If no year is provided, the current year will be used.
* @returns {Array<number>} An array where each index (0-11) represents a month
* (January to December) and the value is the number of days in that month.
* For example, index 0 is January, index 1 is February, etc.
*/
function getDaysInMonths(year) {
// If no year is provided, default to the current year.
const currentYear = year || new Date().getFullYear();
// Check if the currentYear is a leap year.
// A year is a leap year if it is divisible by 4, except for end-of-century years
// which must be divisible by 400.
const isLeapYear = (currentYear % 4 === 0 && currentYear % 100 !== 0) || (currentYear % 400 === 0);
// Initialize an array with the default number of days for each month,
// assuming a non-leap year. January (index 0) through December (index 11).
const days = [
31, // January
28, // February (will be updated for leap years)
31, // March
30, // April
31, // May
30, // June
31, // July
31, // August
30, // September
31, // October
30, // November
31 // December
];
// If it's a leap year, update February's days to 29.
if (isLeapYear) {
days[1] = 29; // February for a leap year
}
// Return the array containing the number of days for each month.
return days;
}
// Example Usage (for demonstration, not part of the function itself):
// const days2023 = getDaysInMonths(2023);
// console.log('Days in months for 2023:', days2023); // Output: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
// const days2024 = getDaysInMonths(2024);
// console.log('Days in months for 2024:', days2024); // Output: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] (2024 is a leap year)
// const daysCurrentYear = getDaysInMonths();
// console.log('Days in months for current year:', daysCurrentYear);
Prompt: the number of days in each month