- 判断日期格式是否正确,可以使用正则表达式
const isDate = function(date) {
const regExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
return regExp.test(date) && !isNaN(new Date(date).getTime());
};
或者使用日期校验方法
const isCheckDate = function(date) {
const res = date.match(/^(\d{1,4})(\-|\/|\.)(\d{1,2})\2(\d{1,2})$/);
if (res !== null) {
const tmpDate = new Date(res[1], parseInt(res[3]) - 1, res[4]);
return tmpDate.getFullYear() === parseInt(res[1]) && tmpDate.getMonth() + 1 === parseInt(res[3]) && tmpDate.getDate() === parseInt(res[4]);
}
return false;
};
- 获取日期区间的日期列表,
const getDateIntervalsList = function(startDate, endDate) {
const isDate = function(date) {
const regExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
return regExp.test(date) && !isNaN(new Date(date).getTime());
};
const dateList = [];
if (isDate(startDate) && isDate(endDate)) {
const sT = new Date(startDate);
const eT = new Date(endDate);
while (eT.getTime() - sT.getTime() >= 0) {
const year = sT.getFullYear();
const month = (sT.getMonth() + 1).toString().padStart(2, '0');
const day = (sT.getDate()).toString().padStart(2, '0');
dateList.push(year + '-' + month + '-' + day);
sT.setDate(sT.getDate() + 1);
}
}
return dateList;
};
···