1

如何检查字符串是否为有效日期?如果它是有效的,我想返回 true,否则返回 false。字符串将类似于 '01-JUN-2012'

4

1 回答 1

1

以下函数检查 (dd MMM yyyy) 格式。不接受破折号 (-)。它可能会帮助您或仔细查看正则表达式以对其进行少量修改..

function isDate(txtDate)
{
    var currVal = txtDate;
    if(currVal == '')
        return false;

    var rxDatePattern = /^((31(?!\(Feb(ruary)?|Apr(il)?|June?|(Sep(?=\b|t)t?|Nov)(ember)?)))|((30|29)(?!\ Feb(ruary)?))|(29(?=\ Feb(ruary)?\ (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\b|t)t?|Nov|Dec)(ember)?)\ ((1[6-9]|[2-9]\d)\d{2})$/; //Declare Regex
    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) 
        return false;

    //Checks for dd MMM yyyy format.

    dtMonth = dtArray[2];

    dtDay= dtArray[1];

    dtYear = dtArray[dtArray.length-2];       



    if (dtDay < 1 || dtDay> 31) 
        return false;
    else if (dtMonth == 2) 
    {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                return false;
    }
    return true;
}

});​

jsFiddle上的工作演示

于 2012-07-06T05:08:15.163 回答