简体   繁体   English

使用正则表达式验证日期

[英]Validating Date with Regex

I need a regex to pattern match the following - 我需要一个正则表达式来匹配以下内容-

mm/dd/yyyy

The following date entries should pass validation: 以下日期条目应通过验证:

  • 05/03/2012 2012年5月3日
  • 5/03/2012 2012年5月3日
  • 05/3/2012 2012年5月3日
  • 5/3/2012 2012年5月3日

Also, after validating above regex , what is the best way convert above date string to Date object? 另外,在验证上述regex ,将上述日期string转换为Date对象的最佳方法是什么?

You should do the check and the parsing in one go, using split, parseInt and the Date constructor : 您应该使用split,parseInt和Date构造函数一次性进行检查和解析:

function toDate(s) {
  var t = s.split('/');
  try {
     if (t.length!=3) return null;
     var d = parseInt(t[1],10);
     var m = parseInt(t[0],10);
     var y = parseInt(t[2],10);
     if (d>0 && d<32 && m>0 && m<13) return new Date(y, m-1, d);
  } catch (e){}
}

var date = toDate(somestring);
if (date) // ok
else // not ok

DEMONSTRATION : 示范:

01/22/2012 ==> Sun Jan 22 2012 00:00:00 GMT+0100 (CET)
07/5/1972 ==> Wed Jul 05 1972 00:00:00 GMT+0100 (CEST)
999/99/1972 ==> invalid

As other answers of this page, this wouldn't choke for 31 in February. 作为此页面的其他答案,2月份不会有31个。 That's why for all serious purposes you should instead use a library like Datejs . 因此,出于所有重要目的,您应该改用Datejs之类的库。

This one should do it: 这应该做到:

((?:[0]?[1-9]|[1][012])[-:\\/.](?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))[-:\\/.](?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])

(It is taken from txt2re.com) (摘自txt2re.com)

You should also take a look at this link . 您还应该查看此链接

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

链接: JavaScript日期正则表达式DD / MM / YYYY

var dateStr = '01/01/1901',
    dateObj = null,
    dateReg = /^(?:0[1-9]|1[012]|[1-9])\/(?:[012][1-9]|3[01]|[1-9])\/(?:19|20)\d\d$/;
    //             01 to 12 or 1 to 9   /    01 to 31  or  1 to 9   /  1900 to 2099

if( dateStr.match( dateReg ) ){
    dateObj = new Date( dateStr ); // this will be in the local timezone
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM