Javascript 如何验证日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5812220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate a date?
提问by Seth Duncan
I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011
then it should be wrong.
我正在尝试测试以确保日期有效,因为如果有人进入,2/30/2011
那么它应该是错误的。
How can I do this with any date?
我怎么能用任何日期做到这一点?
回答by RobG
One simple way to validate a date string is to convert to a date object and test that, e.g.
验证日期字符串的一种简单方法是转换为日期对象并进行测试,例如
// Expect input as d/m/y
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d && (d.getMonth() + 1) == bits[1];
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate(s))
})
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
以这种方式测试日期时,只需要测试月份,因为如果日期超出范围,月份就会改变。如果月份超出范围,则相同。任何年份都有效。
You can also test the bits of the date string:
您还可以测试日期字符串的位:
function isValidDate2(s) {
var bits = s.split('/');
var y = bits[2],
m = bits[1],
d = bits[0];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ((!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate2(s))
})
回答by Piotr Kwiatek
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'? I think NOT, because the YEAR is not validated ;(
RobG 提出的第一个函数 isValidDate(s) 是否适用于输入字符串“1/2/”?我认为不是,因为 YEAR 未经过验证;(
My proposition is to use improved version of this function:
我的提议是使用这个函数的改进版本:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
回答by Luke Cordingley
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
此解决方案不解决明显的日期验证问题,例如确保日期部分是整数或日期部分符合明显的验证检查,例如日期大于 0 且小于 32。此解决方案假定您已经拥有所有三个日期部分(年、月、日)并且每个都已经通过了明显的验证。鉴于这些假设,此方法应该可以用于简单地检查日期是否存在。
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
例如,2009 年 2 月 29 日不是实际日期,但 2008 年 2 月 29 日是。当你创建一个新的 Date 对象时,比如 2009 年 2 月 29 日,看看会发生什么(记住在 JavaScript 中月份是从零开始的):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
以上行输出:Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
请注意日期如何简单地滚动到下个月的第一天。假设您有其他明显的验证,此信息可用于通过以下函数确定日期是否真实(此函数允许使用非零月份以更方便地输入):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
这不是一个完整的解决方案,也没有考虑 i18n,但它可以变得更加健壮。
回答by Dhayalan
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
this function returns bool value of whether the input given is a valid date or not. ex:
此函数返回给定的输入是否为有效日期的布尔值。前任:
if(isDate_(var_date)) {
// statements if the date is valid
} else {
// statements if not valid
}
回答by olivier cherrier
回答by Derekthar
I just do a remake of RobG solution
我只是重新制作了RobG 解决方案
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
回答by forget_me_alice
This is ES6 (with let declaration).
这是 ES6(带有 let 声明)。
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
在这种情况下,我打算使用 1 到 12 个月。如果您更喜欢或使用基于 0-11 的模型,您只需更改数组:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
如果您的日期格式为 dd/mm/yyyy,那么您可以去掉日、月和年函数参数,然后执行以下操作来检索它们:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
回答by Alejandro Reyes
My function returns true if is a valid date otherwise returns false :D
如果是有效日期,我的函数返回 true 否则返回 false :D
function isDate (day, month, year){
if(day == 0 ){
return false;
}
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day > 31)
return false;
return true;
case 2:
if (year % 4 == 0)
if(day > 29){
return false;
}
else{
return true;
}
if(day > 28){
return false;
}
return true;
case 4: case 6: case 9: case 11:
if(day > 30){
return false;
}
return true;
default:
return false;
}
}
console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));
回答by rosenfeld
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
不幸的是,现在 JavaScript 似乎没有简单的方法来验证日期字符串。这是我能想到的在现代浏览器中以“m/d/yyyy”格式解析日期的最简单方法(这就是为什么它没有指定 parseInt 的基数,因为自 ES5 以来它应该是 10):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
if (!dateValidationRegex.test(strDate)) return false;
const [m, d, y] = strDate.split('/').map(n => parseInt(n));
return m === new Date(y, m - 1, d).getMonth() + 1;
}
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
console.log(d, isValidDate(d));
});
回答by Krishnamoorthy Acharya
Hi Please find the answer below.this is done by validating the date newly created
嗨,请在下面找到答案。这是通过验证新创建的日期来完成的
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}