Performance is of the utmost importance on this one guys... This thing needs to be lightning fast!
How would you validate the number of days in a given mont
all this logic is already built in to the javascript engine... Why recode it ? Unless you are doing this just as an exercise, you can use the javascript Date object:
Like this:
function daysInMonth(aDate) {
return new Date(aDate.getYear(), aDate.getMonth()+1, 0).getDate();
}
Assuming the JS Date object standard where months are numbered from 0, and you have your daysInMonth array:
var days = daysInMonth[month] + ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0)));
will give you the number of days in the month, with 28 increased to 29 iff the month is February and the year is a leap year.
You can use DateTime to solve this:
new DateTime('20090901')->format('t'); // gives the days of the month
Have you tried moment.js?
The validation is quite easy to use:
var m = moment("2015-11-32");
m.isValid(); // false
I don't know about the performances but hum the project is stared 11,000+ times on GitHub (kind of a quality guarantee).
Source: http://momentjs.com/docs/#/parsing/is-valid/
function caldays(m,y)
{
if (m == 01 || m == 03 || m == 05 || m == 07 || m == 08 || m == 10 || m == 12)
{
return 31;
}
else if (m == 04 || m == 06 || m == 09 || m == 11)
{
return 30;
}
else
{
if ((y % 4 == 0) || (y % 400 == 0 && y % 100 != 0))
{
return 29;
}
else
{
return 28;
}
}
}
source: http://www.dotnetspider.com/resources/20979-Javascript-code-get-number-days-perticuler-month-year.aspx
This will not perform as well as the accepted answer. I threw this in here because I think it is the simplest code. Most people would not need to optimize this function.
function validateDaysInMonth(year, month, day)
{
if (day < 1 || day > 31 || (new Date(year, month, day)).getMonth() != month)
throw new Error("Frack!");
}
It takes advantage of the fact that the javascript Date constructor will perform date arithmetic on dates that are out of range, e.g., if you do:
var year = 2001; //not a leap year!
var month = 1 //February
var day = 29; //not a valid date for this year
new Date(year, month, day);
the object will return Mar 1st, 2001 as the date.