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

Source: Internet
Author: User

The IsDate function of VBScript is used to determine whether a date is correct. If JavaScript does not have this function, we will also write a similar function. It must be noted that the IsDate parameter in JavaScript must be a string, six different formats are supported: "yyyy-mm-dd | yyyy/mm/dd | dd-mm-yyyy | dd/mm/yyyy | mm-dd- yyyy | mm/dd/yyyy ", the reason why Date cannot be used as a parameter is that JavaScript does not have an incorrect Date, such as new Date (, 30 ), the constructor will automatically convert it to the correct date 2008-03-01. The IsDate function for JavaScript 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;
}
} Webpage 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.