JavaScript 检测有效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8098202/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:43:22  来源:igfitidea点击:

JavaScript Detecting Valid Dates

javascriptjquerydatejquery-validate

提问by Nick Olsen

Possible Duplicate:
Detecting an “invalid date” Date instance in JavaScript

可能的重复:
在 JavaScript 中检测“无效日期”日期实例

I was using the following to detect a valid date:

我使用以下内容来检测有效日期:

var text = $('#Date').val();
var date = Date.parse(text);

if (isNaN(date)) {
      // Invalid date
}

But found that Date.parse thinks the following are valid dates (mm/dd/yyyy)

但是发现Date.parse认为以下是有效日期(mm/dd/yyyy)

  • 2/30/2011
  • 11/31/2011
  • 2/30/2011
  • 11/31/2011

Any other way to detect invalid dates when the number of days surpasses the total number of days in the month?

当天数超过当月的总天数时,还有其他方法可以检测无效日期吗?

UPDATE: An even larger problem is that the jQuery validation plugin doesn't detect this as an invalid date either!

更新:一个更大的问题是 jQuery 验证插件也没有将此检测为无效日期!

SOLUTION:

解决方案:

Based on @Guffa's comments I have created the following function to validate dates:

根据@Guffa 的评论,我创建了以下函数来验证日期:

function validDate(text) {

    var date = Date.parse(text);

    if (isNaN(date)) {
        return false;
    }

    var comp = text.split('/');

    if (comp.length !== 3) {
        return false;
    }

    var m = parseInt(comp[0], 10);
    var d = parseInt(comp[1], 10);
    var y = parseInt(comp[2], 10);
    var date = new Date(y, m - 1, d);
    return (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d);
}

回答by Guffa

To check if a date is valid you can parse the components of the date, create a Dateobject from it, and check if the components in the data is the same as the parsed components. If you create a Dateobject from compnents that are out of range, the values will flow over to the next/previous period to create a valid date.

要检查日期是否有效,您可以解析日期的组件,Date从中创建一个对象,然后检查数据中的组件是否与解析的组件相同。如果您Date从超出范围的组件创建对象,则值将流到下一个/上一个期间以创建有效日期。

For example, new Date(2011,0,42)will create an object that contains the date 2/11/2011 instead of 1/42/2011.

例如,new Date(2011,0,42)将创建一个包含日期 2/11/2011 而不是 1/42/2011 的对象。

By parsing the components instead of the full date you will also get around the problem with different date formats. My browser will for example expect a date format like y-m-drather than d/m/y.

通过解析组件而不是完整日期,您还可以解决不同日期格式的问题。例如,我的浏览器将期望使用日期格式y-m-d而不是d/m/y.

Example:

例子:

var text = '2/30/2011';
var comp = text.split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y,m-1,d);
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
  alert('Valid date');
} else {
  alert('Invalid date');
}

Demo: http://jsfiddle.net/Guffa/UeQAK/

演示:http: //jsfiddle.net/Guffa/UeQAK/

回答by James Clark

If your date format is fixed as M/D/YYYY, you could re-format the parsed date and see if it matches the input:

如果您的日期格式固定为M/D/YYYY,您可以重新格式化解析的日期并查看它是否与输入匹配:

var d = new Date(Date.parse(str))
return str === (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getYear();

However, that won't tolerate whitespace or zero-padded numbers.

但是,这不能容忍空格或零填充数字。

If you don't need to keep the user's input exactly, you could just reformat the date anyway and pretend that was what they typed.

如果您不需要完全保留用户的输入,则无论如何都可以重新格式化日期并假装这是他们输入的内容。

But if you can't do that either, I'd parse out the components myself using a RegExp and then compare them to values from the Datemethods.

但是,如果您也不能这样做,我会使用 RegExp 自己解析组件,然后将它们与Date方法中的值进行比较。

回答by Kevin Anthony Oppegaard Rose

You could write a script to do this manually:

您可以编写一个脚本来手动执行此操作:

function checkDate(day, month) {
   if ((month == 4 || month == 6 || month == 9 || month == 11) && day < 30) {
       alert("Date is valid")
   }
   else if (month == 2 && day <= 28) {
       alert("Date is valid")
   }
   else if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day <= 31) {
       alert("Date is valid")
   }
   else {
       alert("Date is in-valid")
   }
}

Of course, you would also need something to look out for leap years, but just remember that any year divisible by 4 and not by 100 is a leap year unless the first two digits of the year are divisible by 4. That should be easy to include in this function.

当然,您还需要注意闰年,但请记住,任何能被 4 整除而不是 100 整除的年份都是闰年,除非年份的前两位数字能被 4 整除。这应该很容易包含在这个函数中。

回答by Thales Violakis

The example is wrong

例子错了

the correct is

正确的是

if ((month == 4 || month == 6 || month == 9 || month == 11) && day <= 30)

<=instead of =

<=代替 =

But the example are great!

但是这个例子很棒!