我使用文本字段在我的表單中獲取日期,我使用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的)的格式。
如何做到這一點?
yes.its working great ..謝謝 – 2012-01-06 11:32:39
好的答案,但如果您以後需要支持m/d/yy,甚至歐洲風格的dd/mm/yyyy,該怎麼辦?您將不斷需要支持新格式,並且您每次都重新發明輪子。更好地使用圖書館恕我直言。 – Richard 2012-01-06 11:48:43
@Richard我會親自這樣做的。但在某些情況下,可能有理由不引入新的圖書館。當然,你總是在簡單/簡單/簡單的解決方案和麪向未來的解決方案之間進行平衡。 – hleinone 2012-01-06 11:52:28