How to check if a string is a legal “dd/mm/yyyy” date?

前端 未结 7 1904
遥遥无期
遥遥无期 2020-12-01 15:05

Given a string str, how could I check if it is in the dd/mm/yyyy format and contains a legal date ?

Some examples:

bla bla          


        
相关标签:
7条回答
  • 2020-12-01 15:55

    Try -

       var strDate = '12/03/2011';
       var dateParts = strDate.split("/");
       var date = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0]);
    

    There's more info in this question - Parse DateTime string in JavaScript (the code in my answer is heavily influenced by linked question)

    Demo - http://jsfiddle.net/xW2p8/

    EDIT

    Updated answer, try -

    function isValidDate(strDate) {
        if (strDate.length != 10) return false;
        var dateParts = strDate.split("/");
        var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
        if (date.getDate() == dateParts[0] && date.getMonth() == (dateParts[1] - 1) && date.getFullYear() == dateParts[2]) {
            return true;
        }
        else return false;
    }
    

    This function passes all the test cases. As far as I'm aware, Adam Jurczyk had posted an accurate answer well before I corrected my original wrong answer. He deserves credit for this.

    Demo - http://jsfiddle.net/2r6eX/1/

    0 讨论(0)
提交回复
热议问题