javaScript 正则表达式匹配日期

时间:2021-12-25 06:11:43

// yyyyMMddhhmmss
var pattern = /^(?:(?!0000)[0-9]{4}(?:(?:0[1-9]|1[0-2])(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)([01][0-9]|2[0-3])[0-5][0-9][0-5][0-9]$/;
// yyyyMMdd
var pattern = /^(?:(?!0000)[0-9]{4}(?:(?:0[1-9]|1[0-2])(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])(?:29|30)|(?:0[13578]|1[02])31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)0229)$/;
// yyyy-MM-dd HH:mm:ss
var pattern= /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)\s([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;

//yyyy-MM-dd

var pattern = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/;

////HH:mm:ss

var pattern=/^([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;

 

var regExp = new RegExp(pattern);

var value = "20160101"

console.log(regExp.test(value));

//注意:开头和结尾的/符号是在javaScript里才用,并且pattern不能加双引号。如果是希望用在线工具测试时,需把/符号去掉。

参考:https://gist.github.com/x-strong/5378739