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?
Try this:
function numberOfDays(year, month) {
var d = new Date(year, month, 0);
return d.getDate();
}
Because of leap years you need to pass the year too.
function getDaysInMonth(m, y) {
return /8|3|5|10/.test(--m)?30:m==1?(!(y%4)&&y%100)||!(y%400)?29:28:31;
}
Thirty days hath September,
April, June, and November;
All the rest have thirty-one,
Excepting February alone,
Which hath twenty-eight days clear,
And twenty-nine in each leap year.
try this:
function DaysinMonth(aDate) {
return aDate.setMonth(aDate.getMonth()+1, 0).getDate();
}
In the spirit of not doing your homework for you, I present a version in POVRay (sorry, not JS) I did many years ago.
In POVRay, there are no boolean variables. The method I came up with was to create a polynomial in 'm' which gave an answer > 0 for months with 31 days and < 0 for months with 30 days.
#declare m0 = (m-0.5)*(m-1.5)*(m-2.5)*(m-3.5)*(m-4.5)*(m-5.5);
#declare m0 = m0*(m-6.5)*(m-8.5)*(m-9.5)*(m-10.5)*(m-11.5);
#if (m0 > 0)
#declare maxdays = 31;
#else
#declare maxdays = 30;
#end
The tricky part is to decide when the year is a leap year. This is the full test for leap years. Most people are aware of the 4-year rule, and since 2000, some know about the 100 and 400 year rules, there is no 4000 year rule.
#declare LEAPYEAR = 2.0;
#if (mod(YEAR,4.0)=0)
#declare LEAPYEAR = 1.0;
#if (mod(YEAR,100.0)=0)
#declare LEAPYEAR = 2.0;
#end
#if (mod(YEAR,400.0)=0
#declare LEAPYEAR = 1.0;
#end
#end
#if (MONTH = 2.0)
#declare maxdays = maxdays - LEAPYEAR;
#end
#if (DAY > maxdays)
#declare MONTH = MONTH + 1;
#declare DAY = DAY - maxdays;
#end
#if (MONTH > 12)
#declare YEAR = YEAR + 1;
#declare MONTH = MONTH - 12;
#end