【正则校验时间格式】
/**
* 一位数前加0 例:5 -> 05
*/
function set2len(str) {
if (!isNaN(str)) {
str += '';
}
return str.length == 1 ? '0' + str : str;
}
/**
* 日期格式 例: 2021-09-12
*/
function isDate(str) {
if (!str) {
return false;
}
var res = str.match(/^(\d{4})(-)(\d{1,2})\2(\d{1,2})$/);
if (res == null) {
return false;
}
var d = new Date(res[1], Number(res[3])-1, res[4]);
return d.getFullYear() + '-' + set2len(d.getMonth() + 1) + '-' + set2len(d.getDate());
}
/**
* 日期格式 例: 2021-09-12 09:42:01
*/
function isDateTime(str) {
if (!str) {
return false;
}
var res = str.match(/^(\d{4})(-)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
if (res == null) {
return false;
}
var d = new Date(res[1], Number(res[3])-1, res[4], res[5], res[6], res[7]);
return d.getFullYear() + '-'
+ set2len(d.getMonth() + 1) + '-'
+ set2len(d.getDate()) + ' ' +
+ set2len(d.getHours()) + ':' +
+ set2len(d.getMinutes()) + ':' +
+ set2len(d.getSeconds());
}
console.log(isDate("2021-09-12"));
//2021-09-12
console.log(isDate("2021-09-1"));
//2021-09-01
console.log(isDate("2021-9-12"));
//2021-09-12
console.log(isDate("2021-9-120"));
//false
console.log(isDate("1019-009-12"));
//false
console.log(isDate("1019--12"));
//false
console.log(isDate("1019-12"));
//false
console.log(isDate("1019912"));
//false
console.log(isDateTime("2021-09-12 23:59:59"));
//2021-09-12 23:59:59
console.log(isDateTime("2021-09-1 55:3:5"));
//2021-09-03 07:03:05
console.log(isDateTime("2021-9-12 55"));
//false
|