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

发布于 2024-12-07 09:39:48 字数 351 浏览 0 评论 0原文

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

一些例子:

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

旧梦荧光笔 2024-12-14 09:39:48

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

您可以执行类似的操作,但使用更准确的算法进行日验证:

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://www.eee.hiflyers.co.uk/ProgPrac/DateValidation-algorithm.pdf

精确解决方案: 返回解析日期或 null 的函数,完全取决于您的要求。

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/

如果您需要该函数返回 true /false 且适用于 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 ;
}

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/

Date validation alg.: 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/

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

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 ;
}
幸福不弃 2024-12-14 09:39:48

尝试 -

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

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

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

编辑

更新答案,尝试 -

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;
}

该函数通过了所有测试用例。据我所知,在我更正原来的错误答案之前,Adam Jurczyk 就已经发布了准确的答案。他在这一点上值得赞扬。

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

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)

Demo - 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.

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

瀟灑尐姊 2024-12-14 09:39:48

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

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

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

以完全匹配您的要求使用

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

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

  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

for exact match of your requirement use

 re = /^\d{2}\/\d{2}\/\d{4}$/; 
迷荒 2024-12-14 09:39:48

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

   <input type = "date" ...

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

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

   <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.

ま昔日黯然 2024-12-14 09:39:48

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

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

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

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

潇烟暮雨 2024-12-14 09:39:48

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

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

楠木可依 2024-12-14 09:39:48

仅适用于 dd/mm/yyyy 格式

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

for dd/mm/yyyy format only

^(0?[1-9]|[12][0-9]|3[01])[\/](0?[1-9]|1[012])[\/]\d{4}$
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文