I want to validate my date if date not exits in calendar then return me last available date of calendar,
Example 01
Input Date : 31
The last day of the month is given by the zero day of the following month, so:
function getDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getMonth() == month) {
return d;
}
return new Date(year, +month + 1, 0);
}
console.log(getDate(2017,1,29).toString());
console.log(getDate(2017,0,32).toString());
BTW, to test for a valid date you only need to test the month since if the month is larger than months in a year, it will affect both month and year. If the day is greater than the number of days in the month it will affect the month too. Nothing affects the year (unless you pass a year less than 100, in which case it's treated as 1900 + year).