2011-02-16 24 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