JavaScript的Date對象有容錯性,可將隨意給定的日期的年月日自動生成正確的日期時間
//JavaScript中Date對象容錯性 function dateCheck(){ var date = new Date(); date.setDate(date.getDate()+13); //date.setDate(date.getMonth()+1+10); //打印依然能輸出正確的日期 console.log(date.getFullYear()+"年"+(date.getDate())+"日"+(date.getMonth()+1)+"月"); }
由此可以根據Date對象的容錯性對輸入日期的年月日進行正確性判斷,具體代碼如下:
//判斷給定日期是否合法 function checkDate(year,month,date){ var now = new Date(year,month -1,date); if(now.getDate()===date&&now.getFullYear()==year&&now.getMonth()===(month-1)){ return true; } return false; } checkDate(2014,8,34);
