有什么简单的方法来检查一个值是否为有效日期,允许任何已知的日期格式。
例如,我有值10-11-2009、10/11/2009、2009-11-10T07:00:00+0000,这些值都应该被识别为日期值,而值200、10、350不应该被识别为日期值。如果可能的话,最简单的检查方法是什么?因为时间戳也是允许的。
有什么简单的方法来检查一个值是否为有效日期,允许任何已知的日期格式。
例如,我有值10-11-2009、10/11/2009、2009-11-10T07:00:00+0000,这些值都应该被识别为日期值,而值200、10、350不应该被识别为日期值。如果可能的话,最简单的检查方法是什么?因为时间戳也是允许的。
当前回答
该函数验证格式为m/d/yyyy或mm/dd/yyyy的输入字符串是否可以转换为日期,并且该日期是与输入字符串匹配的有效日期。添加更多条件检查来验证其他格式。
/**
* Verify if a string is a date
* @param {string} sDate - string that should be formatted m/d/yyyy or mm/dd/yyyy
* @return {boolean} whether string is a valid date
*/
function isValidDate(sDate) {
let newDate = new Date(sDate);
console.log(sDate + " date conversion: " + newDate);
let isDate = (!isNaN(newDate.getTime()));
console.log(sDate + " is a date: " + isDate);
if (isDate) {
let firstSlash = sDate.indexOf("/");
let secondSlash = sDate.indexOf("/",firstSlash+1);
let originalDateString = parseInt(sDate.slice(0,firstSlash),10) + "/" + parseInt(sDate.slice(firstSlash+1,secondSlash),10) + "/" + parseInt(sDate.slice(secondSlash+1),10);
let newDateString = (newDate.getMonth()+1) + "/" + (newDate.getDate()) + "/" + (newDate.getFullYear());
isDate = (originalDateString == newDateString);
console.log(originalDateString + " matches " + newDateString + ": " + isDate);
}
return isDate;
}
其他回答
下面是一个只使用Date.parse()的改进函数:
function isDate(s) {
if(isNaN(s) && !isNaN(Date.parse(s)))
return true;
else return false;
}
注意:date. parse()将解析数字:例如date. parse(1)将返回日期。这里我们检查s是不是数字,是不是日期。
通过参考以上所有的评论,我已经找到了一个解决方案。
如果传递的日期是ISO格式或需要为其他格式操作,则此方法有效。
var isISO = "2018-08-01T18:30:00.000Z";
if (new Date(isISO) !== "Invalid Date" && !isNaN(new Date(isISO))) {
if(isISO == new Date(isISO).toISOString()) {
console.log("Valid date");
} else {
console.log("Invalid date");
}
} else {
console.log("Invalid date");
}
你可以在JSFiddle上玩。
下面是可以用来验证输入是否为可以转换为日期对象的数字或字符串的方法。
它涵盖以下情况:
捕获任何导致“无效日期”日期构造函数结果的输入; 捕捉从技术角度来看日期是“有效的”,但从业务逻辑角度来看它是无效的情况,例如
new Date(null).getTime(): 0 new Date(true).getTime(): 1 new Date(-3.14).getTime(): -3 new Date(["1", "2"]).toDateString(): Tue Jan 02 2001 new Date([1,2]).toDateString(): Tue Jan 02 2001
function checkDateInputValidity(input, lowerLimit, upperLimit) {
// make sure the input is a number or string to avoid false positive correct dates:
if (...) {
return false
}
// create the date object:
const date = new Date(input)
// check if the Date constructor failed:
if (date.toDateString() === 'Invalid Date') {
return false
}
// check if the Date constructor succeeded, but the result is out of range:
if (date < new Date(lowerLimit) || date > new Date(upperLimit)) {
return false
}
return true
}
// const low = '2021-12-31T23:59:59'
// const high = '2025-01-01T00:00:00'
该函数验证格式为m/d/yyyy或mm/dd/yyyy的输入字符串是否可以转换为日期,并且该日期是与输入字符串匹配的有效日期。添加更多条件检查来验证其他格式。
/**
* Verify if a string is a date
* @param {string} sDate - string that should be formatted m/d/yyyy or mm/dd/yyyy
* @return {boolean} whether string is a valid date
*/
function isValidDate(sDate) {
let newDate = new Date(sDate);
console.log(sDate + " date conversion: " + newDate);
let isDate = (!isNaN(newDate.getTime()));
console.log(sDate + " is a date: " + isDate);
if (isDate) {
let firstSlash = sDate.indexOf("/");
let secondSlash = sDate.indexOf("/",firstSlash+1);
let originalDateString = parseInt(sDate.slice(0,firstSlash),10) + "/" + parseInt(sDate.slice(firstSlash+1,secondSlash),10) + "/" + parseInt(sDate.slice(secondSlash+1),10);
let newDateString = (newDate.getMonth()+1) + "/" + (newDate.getDate()) + "/" + (newDate.getFullYear());
isDate = (originalDateString == newDateString);
console.log(originalDateString + " matches " + newDateString + ": " + isDate);
}
return isDate;
}
我就是这么做的。这不会涵盖所有格式。 你必须相应地调整。我可以控制格式,所以它适合我
function isValidDate(s) {
var dt = "";
var bits = [];
if (s && s.length >= 6) {
if (s.indexOf("/") > -1) {
bits = s.split("/");
}
else if (s.indexOf("-") > -1) {
bits = s.split("-");
}
else if (s.indexOf(".") > -1) {
bits = s.split(".");
}
try {
dt = new Date(bits[2], bits[0] - 1, bits[1]);
} catch (e) {
return false;
}
return (dt.getMonth() + 1) === parseInt(bits[0]);
} else {
return false;
}
}