2012-10-17 148 views
1

我需要一个正则表达式匹配模式下 -验证日期与正则表达式

mm/dd/yyyy 

下列日期项应通过验证:

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

此外,验证以上regex后,将以上日期string转换为Date对象的最佳方式是什么?

+1

http://www.regular-expressions.info/dates.html只需调整日期组件 –

回答

1

你应该做的检查,并一气呵成解析,采用分体式,parseInt函数和the Date constructor

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 

由于该网页的其他答案,这不会呛二月份为31。这就是为什么对于所有严重的目的,你应该使用像Datejs这样的图书馆。

+1

有趣的解决方案的顺序,但它会很乐意接受99/99/99作为有效日期。 JavaScript日期函数将从任何数值生成有效日期。你应该在调用日期之前验证它们。 – HBP

+0

@HBP +1你是对的......我没有想到这一点。我会解决它。 –

+0

@HBP但作为其他答案,2012年2月31日仍然很开心。所以我建议使用像Datejs这样的库(或者其他的,但我使用Datejs没有问题)。 –

0

这一次应该这样做:

((?:[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]) 

(它是由txt2re.com拍摄)

你也应该看看this link

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