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.