How can I write a JavaScript function that accepts a number from 1 - 12 representing the months of the year, and then returns the number of days in that month?
No? Well, there's a good reason for that and you've probably already guessed it: those aren't even real days! If you check your calendar, you'll notice that February only has 28 days (unless it's a leap year), September only has 30 days, October only has 31 days, and November only has 30 days.
Just about every elementary schooler learns the months of the year with an easy rhyme: “Thirty days has [or hath] September, April, June, and November. All the rest have 31, except February …” The leap year, which comes once in four / Gives February one day more.”
How Many Have 28, 29, 30, or 31 Days? The Gregorian calendar has 4 months that are 30 days long and 7 months that are 31 days long. February is the only month that is 28 days long in common years and 29 days long in leap years.
function getDaysInMonth(m, y) {
return /8|3|5|10/.test(--m)?30:m==1?(!(y%4)&&y%100)||!(y%400)?29:28:31;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With