Js Method for judging the validity of a date and a js method for judging the validity of a date

Source: Internet
Author: User

Js Method for judging the validity of a date and a js method for judging the validity of a date

Two methods to verify date and time using javascript are provided.
First:

// | Date validity verification // | format: YYYY-MM-DD or YYYY/MM/DD function IsValidDate (DateStr) {var sDate = DateStr. replace (/(^ \ s + | \ s + $)/g, ''); // remove spaces on both sides; if (sDate ='') {return true ;} // if the format is YYYY-(/) MM-(/) DD Or YYYY-(/) M -(/) D or YYYY-(/) MM-(/) D is replaced with ''// database, valid date can be: YYYY-MM/DD ), the database automatically converts to the YYYY-MM-DD format var s = sDate. replace (/[\ d] {4, 4} [\-/] {1} [\ d] {1} [\-/] {1} [\ d] {1, 2} /g, ''); if (s ='') {// The description format meets the YYYY-MM-DD or YYYY -M-DD or YYYY-M-D or YYYY-MM-D var t = new Date (sDate. replace (/\-/g, '/'); var ar = sDate. split (/[-/:]/); if (ar [0]! = T. getYear () | ar [1]! = T. getMonth () + 1 | ar [2]! = T. getDate () {// alert ('incorrect date format! Format: YYYY-MM-DD or YYYY/MM/DD. Pay attention to the leap year. '); Return false ;}} else {// alert (' incorrect date format! Format: YYYY-MM-DD or YYYY/MM/DD. Pay attention to the leap year. '); Return false;} return true ;}

Second:

// | Date and time validity check // | format: YYYY-MM-DD HH: MM: SS function CheckDateTime (str) {var reg =/^ (\ d +) -(\ d {}) :( \ d {}) $ /; var r = str. match (reg); if (r = null) return false; r [2] = r [2]-1; var d = new Date (r [1], r [2], r [3], r [4], r [5], r [6]); if (d. getFullYear ()! = R [1]) return false; if (d. getMonth ()! = R [2]) return false; if (d. getDate ()! = R [3]) return false; if (d. getHours ()! = R [4]) return false; if (d. getMinutes ()! = R [5]) return false; if (d. getSeconds ()! = R [6]) return false; return true ;}

I hope you will like the above two methods.

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.