JavaScript Tutorial: A function to determine whether a date is correct or not

Source: Internet
Author: User
Tags getdate

VBScript's IsDate function is used to determine whether a date is correct, JavaScript does not have this function, and we also write a similar function. It is important to note that isdate parameters in JavaScript must be strings and support 6 different formats "YYYY-MM-DD | | Yyyy/mm/dd | | dd-mm-yyyy | | dd/mm/yyyy | | mm-dd-yyyy | | Mm/dd/yyyy ", the reason why you can't use a date as a parameter is because JavaScript doesn't have an incorrect date, such as new Date (2008,01,30), and the constructor automatically converts it to the correct date 2008-03-01. The JavaScript version IsDate function is as follows:

Function IsDate (dateval) {
    var arr = new Array ();
   
     if (Dateval.indexof ("-")!=-1) {
        arr = dateval.tostring (). Split ( "-");
   }else if (Dateval.indexof ("/")!=-1) {
        arr = Dateval.tostring (). Split ("/");
   }else{
        return false;
   }
   
   //yyyy-mm-dd | | yyyy/mm/dd
    if (arr[0].length==4) {
        var date = new Date (arr[0],arr[1]-1,arr[2]);
        if (Date.getfullyear () ==arr[0] && date.getmonth () ==arr[1]-1 && date.getdate () ==arr[2]) {
            return True
       }

}
dd-mm-yyyy | | Dd/mm/yyyy
if (arr[2].length==4) {
var date = new Date (arr[2],arr[1]-1,arr[0]);
if (Date.getfullyear () ==arr[2] && date.getmonth () ==arr[1]-1 && date.getdate () ==arr[0]) {
return true;
}
}
mm-dd-yyyy | | Mm/dd/yyyy
if (arr[2].length==4) {
var date = new Date (arr[2],arr[0]-1,arr[1]);
if (Date.getfullyear () ==arr[2] && date.getmonth () ==arr[0]-1 && date.getdate () ==arr[1]) {
return true;
}
Web Teaching Network

return false;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.