2011-02-16 27 views
4

我试图解析所有月份格式为January 1, 1900February 1, 1900等的日期..然后将月份,日期和年份分隔到自己的对象中。在没有DateJS的jQuery中的解析日期

我一直在使用,但一个彻头彻尾的现成的正则表达式这个尝试:

  1. 这种特殊的正则表达式似乎过于复杂和像它可以轻松突破
  2. 必须有一个更简单的正则表达式使用知道格式不会改变(我们将验证在后端日期)

我不想使用DateJS库,因为它似乎很多代码包括只是为了解析一个日期,那么是否有更简单的方法来编写regul ar表达这个?除了做正则表达式或DateJS以外,还有其他路线吗?

无论出于什么原因,正则表达式在2月份都不起作用,正如你所看到的,它会返回数组中的相当多的对象,而如果它返回3个对象(月,日,年) 。以下是我用正则表达式编写的当前函数...:

function convertDate(dateString) { 
    // must be in the format MMMMMMM DD, YYYY OR MMM DD, YYYY 
    // examples: January 1, 2000 or Jan 1, 2000 (notice no period for abbreviating January into Jan) 
    var dateRegex = new RegExp('^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sept|Nov|Dec)(ember)?)\\ (0?[1-9]|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,\\ ((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))))\\,\\ ((1[6-9]|[2-9]\\d)\\d{2}))'); 
    var fullDate = dateString.match(dateRegex); 
    console.log(fullDate); 

    if (fullDate) { 
     var month = fullDate[12]; 
     var day = fullDate[24]; 
     var year = fullDate[35]; 

     if (month == 'January' | month == 'Jan') { integerMonth = 1; } 
     else if (month == 'February' | month == 'Feb') { integerMonth = 2; } 
     else if (month == 'March' | month == 'Mar') { integerMonth = 3; } 
     else if (month == 'April' | month == 'Apr') { integerMonth = 4; } 
     else if (month == 'May') { integerMonth = 5; } 
     else if (month == 'June' | month == 'Jun') { integerMonth = 6; } 
     else if (month == 'July' | month == 'Jul') { integerMonth = 7; } 
     else if (month == 'August' | month == 'Aug') { integerMonth = 8; } 
     else if (month == 'September' | month == 'Sep') { integerMonth = 9; } 
     else if (month == 'October' | month == 'Oct') { integerMonth = 10; } 
     else if (month == 'November' | month == 'Nov') { integerMonth = 11; } 
     else if (month == 'December' | month == 'Dec') { integerMonth = 12; } 

     return {month : integerMonth, day : day, year : year} 
    } else { 
     return false; 
    } 
} 

回答

5

javascript日期对象可以用字符串初始化,并且它会解析您使用到正确的日期格式:

var d = new Date("January 1, 2000"); 
if (!isNaN(d.getMonth()) { // check for invalid date 
    return {month : d.getMonth()+1, day : d.getDate(), year : d.getFullYear()}; 
} else { 
    return false; 
} 

正如你所看到的,这个功能是有点难更简单,并且应该在所有现代浏览器中受到支持。

1

这将工作,但不会针对数月和数年。它只需要3-9个字母,一个或两个数字,一个逗号和四个数字。

/^[a-z]{3,9} [0-9]{1,2}, [0-9]{4}$/i 
+0

Thanks Nalum!有没有办法将元素分离到数组中?目前如果我这样做:`var fullDate = dateString.match(/^[az] {3,9} [0-9] {1,2},[0-9] {4} $/i);`我只是得到一个返回值,这是整个日期而不是“一月”“1”“1900” – iwasrobbed 2011-02-16 17:48:54

+0

啊,没关系。我想出了反向引用,现在我有:`var fullDate = dateString.match(/ ^([az] {3,9})([0-9] {1,2}),([0-9] {4 })$/i);`我把它们放到一个数组中 – iwasrobbed 2011-02-16 17:51:10