Javascript 如何检查字符串是否是合法的“dd/mm/yyyy”日期?

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

How to check if a string is a legal "dd/mm/yyyy" date?

javascriptjquerystringdatedate-format

提问by Misha Moroshko

Given a string str, how could I check if it is in the dd/mm/yyyyformat and contains a legal date ?

给定一个字符串str,我如何检查它是否符合dd/mm/yyyy格式并包含合法日期?

Some examples:

一些例子:

bla bla      // false
14/09/2011   //         true
09/14/2011   // false
14/9/2011    // false
1/09/2011    // false
14/09/11     // false
14.09.2011   // false
14/00/2011   // false
29/02/2011   // false
14/09/9999   //         true

回答by Adam Jurczyk

Edit: exact solution below

编辑:下面的确切解决方案

You could do something like this, but with a more accurate algorithm for day validation:

你可以做这样的事情,但使用更准确的算法进行日间验证:

function testDate(str) {
  var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if(t === null)
    return false;
  var d = +t[1], m = +t[2], y = +t[3];

  // Below should be a more acurate algorithm
  if(m >= 1 && m <= 12 && d >= 1 && d <= 31) {
    return true;  
  }

  return false;
}

http://jsfiddle.net/aMWtj/

http://jsfiddle.net/aMWtj/

Date validation alg.: http://www.eee.hiflyers.co.uk/ProgPrac/DateValidation-algorithm.pdf

日期验证算法:http://www.eee.hiflyers.co.uk/ProgPrac/DateValidation-algorithm.pdf

Exact solution:function that returns a parsed date or null, depending exactly on your requirements.

确切的解决方案:返回解析日期或空值的函数,具体取决于您的要求。

function parseDate(str) {
  var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if(t !== null){
    var d = +t[1], m = +t[2], y = +t[3];
    var date = new Date(y, m - 1, d);
    if(date.getFullYear() === y && date.getMonth() === m - 1) {
      return date;   
    }
  }

  return null;
}

http://jsfiddle.net/aMWtj/2/

http://jsfiddle.net/aMWtj/2/

In case you need the function to return true/false and for a yyyy/mm/dd format

如果您需要函数返回真/假和 yyyy/mm/dd 格式

function IsValidDate(pText) {
    var isValid = false ;
    var t = pText.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);

    if (t !== null) {
        var y = +t[1], m = +t[2], d = +t[3];
        var date = new Date(y, m - 1, d);

        isValid = (date.getFullYear() === y && date.getMonth() === m - 1) ;
    }

    return isValid ;
}

回答by ipr101

Try -

尝试 -

   var strDate = '12/03/2011';
   var dateParts = strDate.split("/");
   var date = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0]);

There's more info in this question - Parse DateTime string in JavaScript(the code in my answer is heavily influenced by linked question)

这个问题有更多信息 - Parse DateTime string in JavaScript(我的答案中的代码受链接问题的影响很大)

Demo - http://jsfiddle.net/xW2p8/

演示 - http://jsfiddle.net/xW2p8/

EDIT

编辑

Updated answer, try -

更新的答案,尝试 -

function isValidDate(strDate) {
    if (strDate.length != 10) return false;
    var dateParts = strDate.split("/");
    var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
    if (date.getDate() == dateParts[0] && date.getMonth() == (dateParts[1] - 1) && date.getFullYear() == dateParts[2]) {
        return true;
    }
    else return false;
}

This function passes all the test cases. As far as I'm aware, Adam Jurczyk had posted an accurate answer well before I corrected my original wrong answer. He deserves credit for this.

该函数通过了所有测试用例。据我所知,在我更正最初的错误答案之前,Adam Jurczyk 已经发布了一个准确的答案。他值得称赞。

Demo - http://jsfiddle.net/2r6eX/1/

演示 - http://jsfiddle.net/2r6eX/1/

回答by Pranav

you can use regular exp to validate date . try like this :

您可以使用常规 exp 来验证日期。试试这样:

  re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; 
if(form.mydate.value != '' && !form.mydate.value.match(re))
  //do something here

note: this will only work for dd/mm/yyyy

注意:这仅适用于 dd/mm/yyyy

for exact match of your requirement use

为了完全匹配您的要求使用

 re = /^\d{2}\/\d{2}\/\d{4}$/; 

回答by Cameron Laird

I'm going to answer a different question, as Misha Moroshko's has already been well-answered: use HTML5. That is, on the assumption that the strings in question arise as user inputs through a Web browser, I propose that the entries be received as

我将回答一个不同的问题,因为 Misha Moroshko 已经得到了很好的回答:使用 HTML5。也就是说,假设有问题的字符串是用户通过 Web 浏览器输入的内容,我建议将条目作为

   <input type = "date" ...

I recognize that not all browsers likely to be in use will interpret "date" in a way that rigorously enforces validity. It's the right thing to do, though, will certainly improve as time goes on, and might well be good enough in a particular context even now simply to eliminate the need to validate the date-string after the fact.

我认识到并非所有可能使用的浏览器都会以严格执行有效性的方式解释“日期”。但是,这是正确的做法,随着时间的推移肯定会改进,并且即使在特定上下文中也可能足够好,即使只是为了消除事后验证日期字符串的需要。

回答by NotMe

Personally, I think the best solution would be to modify the UI to use dropdowns for the month and possibly day selections.

就个人而言,我认为最好的解决方案是修改 UI 以使用月份和可能的日期选择的下拉菜单。

Trying to figure out if 1/2/2001 is January 2nd or February 1st based solely on that input string is impossible.

试图仅根据该输入字符串确定 1/2/2001 是 1 月 2 日还是 2 月 1 日是不可能的。

回答by Adam Jurczyk

Recent discovery:You can use date.jslib, it adds function Date.parseExactso you can just do Date.parseExact(dateString,"dd/MM/yyyy"). It fails when month is 00, but its still usefull.

最近发现:你可以使用date.jslib,它添加了函数Date.parseExact所以你可以做Date.parseExact(dateString,"dd/MM/yyyy"). 当月份为 时它会失败00,但它仍然有用。

回答by Adam Jurczyk

for dd/mm/yyyy format only

仅适用于 dd/mm/yyyy 格式

^(0?[1-9]|[12][0-9]|3[01])[\/](0?[1-9]|1[012])[\/]\d{4}$