因此,我试图用以下代码验证bith的日期,但我在实现if语句时遇到了问题,该语句检查month
是否大于12,它应该抛出一个错误,如果day
大于31,它也应该这样做。我非常感谢你的帮助。
function isYearCorrect(string) {
let dateOfBirth = new Date((string.substring(0, 2)), (string.substring(2, 4) - 1), (string.substring(4, 6)))
let year = dateOfBirth.getFullYear();
let month = dateOfBirth.getMonth() + 1;
let day = dateOfBirth.getDate();
let isDOBValid = false;
if (month < 10) {
month = "0" + month;
}
/**This statement does not check to see if the month ranges from 1 - 12 but it skips
to the next year and month and leaves the day as is. Basically 971315 becomes 1998-01-15*/
if (month > 12) {
return (`${month} is an invalid month`)
} else {
month;
}
if (day < 10) {
day = "0" + day;
} if (day > 31) {
return (`${day} is an invalid month`);
}else {
day;
}
let fullDate = `${year}-${month}-${day}`;
let dateRegex = /^([12]d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01]))$/;
if (dateRegex.test(fullDate) == false) {
isDOBValid;
} else if (dateRegex.test(fullDate) == true) {
isDOBValid = true;
}
return isDOBValid;
}
console.log(isYearCorrect("970812"))
console.log(isYearCorrect("721329"))
在将string
转换为日期之前,您需要设置验证检查条件。
function isYearCorrect(string) {
let yearPiece = +string.substring(0, 2);
let monthPiece = +string.substring(2, 4);
let dayPiece = +string.substring(4, 6);
if (monthPiece > 12) {
return (`${monthPiece} is an invalid month`)
}
if (dayPiece > 31) {
return (`${dayPiece} is an invalid month`);
}
let dateOfBirth = new Date(yearPiece, monthPiece, dayPiece)
let year = dateOfBirth.getFullYear();
let month = dateOfBirth.getMonth() + 1;
let day = dateOfBirth.getDate();
let isDOBValid = false;
/**This statement does not check to see if the month ranges from 1 - 12 but it skips
to the next year and month and leaves the day as is. Basically 971315 becomes 1998-01-15*/
if (month < 10) {
month = "0" + monthPiece;
}
if (day < 10) {
day = "0" + day;
}
let fullDate = `${year}-${month}-${day}`;
let dateRegex = /^([12]d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01]))$/;
if (dateRegex.test(fullDate)) {
isDOBValid = true;
}
return isDOBValid;
}
console.log(isYearCorrect("970812"))
console.log(isYearCorrect("721329"))
TLDR:按设计工作。
解决方案是在将字符串放入新的Date构造函数之前解析字符串,因为您试图做的事情在某种程度上已经由Date对象完成了。
正在发生的事情是,日期是";聪明的";它防止无效日期并触发内部机制,因此当您例如用值"调用此函数时;721429";这被认为是无效的;1973-3-1";。这是正确的(记住二月更短(。
在这里,您可以阅读更多关于日期本身及其可接受的构造函数的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
更重要的是,我建议不要使用";字符串";作为变量的名称,并在可能的情况下使用const(例如regex或fullDate变量(。