Javascript Date 判斷輸入日期是否正確


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);

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM