有什么简单的方法来检查一个值是否为有效日期,允许任何已知的日期格式。
例如,我有值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不应该被识别为日期值。如果可能的话,最简单的检查方法是什么?因为时间戳也是允许的。
当前回答
这个可调用函数工作得很好,有效日期返回true。 请确保使用ISO格式的日期(yyyy-mm-dd或yyyy/mm/dd)调用:
function validateDate(isoDate) {
if (isNaN(Date.parse(isoDate))) {
return false;
} else {
if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
return false;
}
}
return true;
}
其他回答
我认为最直接的解决办法是
Date.parse(yourDate) > 0 ? true : false;
如果不是有效日期,则为NaN, NaN不大于0。
这个可调用函数工作得很好,有效日期返回true。 请确保使用ISO格式的日期(yyyy-mm-dd或yyyy/mm/dd)调用:
function validateDate(isoDate) {
if (isNaN(Date.parse(isoDate))) {
return false;
} else {
if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
return false;
}
}
return true;
}
该函数验证格式为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;
}
好吧,这是一个老问题,但我在检查这里的解时找到了另一个解。For me工作检查函数getTime()是否存在于日期对象:
const checkDate = new Date(dateString);
if (typeof checkDate.getTime !== 'function') {
return;
}
像这样的怎么样?它将测试它是一个Date对象还是一个日期字符串:
function isDate(value) {
var dateFormat;
if (toString.call(value) === '[object Date]') {
return true;
}
if (typeof value.replace === 'function') {
value.replace(/^\s+|\s+$/gm, '');
}
dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})(\s*(?:0?[1-9]:[0-5]|1(?=[012])\d:[0-5])\d\s*[ap]m)?$/;
return dateFormat.test(value);
}
我应该提到的是,这并不测试ISO格式的字符串,但只要再对RegExp做一些工作,您就可以了。