JavaScriptvalidation日期并返回日历的最后可用日期

如果日期不在日历中退出,我想validation我的日期,然后返回我最后一个日历日期,

例01

Input Date : 31-Feb-2017 Return Result : 28-Feb-2017 

例02

 Input Date : 31-March-2017 Return Result : 31-March-2017 

例03

 Input Date : 31-Apr-2017 Return Result : 30-Apr-2017 

例04

 Input Date : 31-Jun-2017 Return Result : 30-Jun-2017 

叶年的例05

 Input Date : 31-Feb-2020 Return Result : 29-Feb-2020 

这是我首先尝试使用以下函数validation日期,我如何为上述日期制作逻辑。

 function isValidDate(year, month, day) { var d = new Date(year, month, day); if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) { return true; } return false; } 

你可以尝试这样的事情:

按规格说明 :

当我们使用2个或更多参数调用date构造函数时,它会尝试使用以下构造函数ref来处理:

 new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] ) 

这里,如果没有传递任何值,它将被设置为NaN ,稍后将被解析为+0 。 因此时间戳为0:0:0

现在的诀窍在于内部调用的函数: MakeDay 。

当你看到第8点时,它会返回

 Day(t) + dt − 1 

这里Day(t)将返回毫秒数,并且日期将基于dt - 1计算。 由于我们传递的是0 ,因此日期值为-1 + milliseconds ,因此它返回前一天。

另一种替代方法是创建下个月1 day日期,并将1减去daysec 。 您可以根据需要选择任何人,

 function isValidDate(year, month, day) { var d = new Date(year, month, day); return !!(d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) } function computeLastPossibleDate(y,m,d){ return new Date(y, m+1, 0); } function test(y,m,d){ return isValidDate(y,m,d) ? new Date(y,m,d) : computeLastPossibleDate(y,m,d) } // 31st Feb. console.log(test(2017, 1, 31).toString()) // 31st March console.log(test(2017, 2, 31).toString()) // 31st April console.log(test(2017, 3, 31).toString()) // 50th Dec. console.log(test(2017, 11, 50).toString()) 

该月的最后一天是下个月的零日,因此:

 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()); 
 function isValidDate(year, month, day) { var d = new Date(year, month, day); if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) { return d; } else rturn new Date(year, month, 0);; } 
  function isValidDate(year, month, day) { if(month<=12){ var temp_day=day; var d = new Date(year, month, day); var lastDay = new Date(d.getFullYear(), d.getMonth(),0); var getlastday=lastDay.getDate(); if(getlastday<=day){ //var date=(d.getDate())+"/"+(d.getMonth())+"/"+(d.getFullYear()); var date=(getlastday)+"-"+(month)+"-"+(lastDay.getFullYear()); return date; }else{ //var date=(lastDay.getDate())+"-"+(lastDay.getMonth())+"-"+(lastDay.getFullYear()); var date=(day)+"/"+(month)+"/"+(year); return date; } } else{ return "month not valid"; } } 

试试这段代码