2012-01-06 30 views
0

我使用文本字段在我的表單中獲取日期,我使用jQuery日期編碼進行日期驗證(mm/dd/yyyy)。如何使用jquery支持01/01/2010和1/1/2010日期格式?

function isDate(txtDate) { 
    var objDate, // date object initialized from the txtDate string 
     mSeconds, // txtDate in milliseconds 
     day,  // day 
     month, // month 
     year;  // year 
    // date length should be 10 characters (no more no less) 
    if (txtDate.length !== 10) { 
     return false; 
    } 
    // third and sixth character should be '/' 
    if (txtDate.substring(2, 3) !== '/' || txtDate.substring(5, 6) !== '/') { 
     return false; 
    } 
    // extract month, day and year from the txtDate (expected format is mm/dd/yyyy) 
    // subtraction will cast variables to integer implicitly (needed 
    // for !== comparing) 
    month = txtDate.substring(0, 2) - 1; // because months in JS start from 0 
    day = txtDate.substring(3, 5) - 0; 
    year = txtDate.substring(6, 10) - 0; 
    // test year range 
    if (year < 1000 || year > 3000) { 
     return false; 
    } 
    // convert txtDate to milliseconds 
    mSeconds = (new Date(year, month, day)).getTime(); 
    // initialize Date() object from calculated milliseconds 
    objDate = new Date(); 
    objDate.setTime(mSeconds); 
    // compare input date and parts from Date() object 
    // if difference exists then date isn't valid 
    if (objDate.getFullYear() !== year || 
     objDate.getMonth() !== month || 
     objDate.getDate() !== day) { 
     return false; 
    } 
    // otherwise return true 
    return true; 
} 

此工作正常的日期格式(月/日/年)..但現在我需要支持像(M/d/yyyy的)的格式。

如何做到這一點?

回答

0

你用這些修改的例子就是支持這兩種格式:

// date length should be between 8 and 10 characters (no more no less) 
if (txtDate.length < 8 || txtDate.length > 10) { 
    return false; 
} 

var tokens = txtDate.split('/'); 
// there should be exactly three tokens 
if (tokens.length !== 3) { 
    return false; 
} 

// extract month, day and year from the txtDate 
month = parseInt(tokens[0]) - 1; // because months in JS start from 0 
day = parseInt(tokens[1]); 
year = parseInt(tokens[2]); 
+0

yes.its working great ..謝謝 – 2012-01-06 11:32:39

+0

好的答案,但如果您以後需要支持m/d/yy,甚至歐洲風格的dd/mm/yyyy,該怎麼辦?您將不斷需要支持新格式,並且您每次都重新發明輪子。更好地使用圖書館恕我直言。 – Richard 2012-01-06 11:48:43

+0

@Richard我會親自這樣做的。但在某些情況下,可能有理由不引入新的圖書館。當然,你總是在簡單/簡單/簡單的解決方案和麪向未來的解決方案之間進行平衡。 – hleinone 2012-01-06 11:52:28

0

嘗試date.js

這樣,您可以編寫代碼如下所示:

Date.parse('7/1/2004')   // Thu Jul 01 2004 

所有解析在Date.js中可以通過包含包含文化信息的文件進行全球化,所以你應該b能夠讓它做到你想要的。

所有你所要做的就是在您的網頁下面的文件開始:

<script type="text/javascript" src="date.js"></script> 
<script type="text/javascript" src="date-de-DE.js"></script> 

編輯

Date.js現在似乎是死了,但Moment.js樣子一個很好的選擇。

+0

date.js是非常死的項目。如果作者願意使用日期處理庫,我會建議[moment.js](http://momentjs.com/)。 – hleinone 2012-01-06 11:41:44

+0

@hleinone布里爾!我從來沒有聽說過moment.js,但是一個很棒的提示。將它添加到我的Javascript書籤列表中。 – Richard 2012-01-06 11:43:56