Home > Enterprise >  the number of days in the given month of the given year
the number of days in the given month of the given year

Time:10-10

I have such a probelm. It consists of two parts

  1. Write a JS code that determines whether a given year is a leap year.

  2. Write a JS code for a program that determines the number of days in the given month of a given year by utilizing the solution to the previous problem as a predefined process/function call.

Thank you in advance.

CodePudding user response:

This should work:

function isLeapYear(year){
  return(year%4==0);
}
console.log(isLeapYear(2024));
console.log(isLeapYear(2023));
function daysInMonth(month,year){
  if (month!=2){
    a=[1,3,5,7,8,10,12]
    for (x in a){
      if (month==a[x]){
        return(31)
      }
    }
    return(30);
  }else{
    if (isLeapYear(year)){
      return(29);
    }else{
      return(28)
    }
  }
}
console.log(daysInMonth(2,2024))
console.log(daysInMonth(2,2023))
console.log(daysInMonth(1,2023))
console.log(daysInMonth(4,2023))

[edit] Sorry about that. Anyway, the first function returns true if the year is a leap year. The second function returns the amount of days in the specified month of the year. That should be better.

  • Related