How to get the number of days in a given month of a given year with TypeScript

1 Answer

0 votes
function isLeapYear(year: number): boolean {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

function daysInMonth(year: number, month: number): number {
    const days: number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    if (month === 2 && isLeapYear(year)) {
        return 29;
    }
    
    return days[month - 1];
}

const year1: number = 2024;
const month1: number = 2;
console.log(`Days in month: ${daysInMonth(year1, month1)}`);
console.log(`Days in month: ${daysInMonth(2025, 1)}`);
console.log(`Days in month: ${daysInMonth(2025, 2)}`);
console.log(`Days in month: ${daysInMonth(2025, 4)}`);

  
  
/*
run:
  
"Days in month: 29" 
"Days in month: 31" 
"Days in month: 28" 
"Days in month: 30" 
  
*/

 



answered Feb 19 by avibootz
...