2013年12月26日 星期四

Javascript 如何檢查日期的合法性? How to check the DATE is valid in Javascript?


其實如果是用 DateTime Picker 就應該不會有這樣的需求,
但規劃是用 年 / 月 / 日 各別的下拉選單,就有可能出現像是 2月30 or 31這樣的日期。
而且如果還要自行判斷是否為閏年或是大小月就更麻煩了。

利用 Javescript 中的 Date Object 來幫忙做處理是最方便不過的。
但是 Date Object 中卻沒有 method 可以用來做日期的合法檢查。

.valueOf().getTime() 是會回傳 NaN 沒錯,但那只有在日期是超過處理範圍時才會發生。

new Date( '2005-02-31' ) 並不會被認為非法,但最後會被轉換為 '2005-03-03'

所以也正好利用這個點去檢查,是否輸入的日期是合法的。

// 傳入 年月日 檢查是否為合法日期
function validDate( _year, _month, _day )
{
  var Day = new Date( _year+ '-' + _month+ '-' + _day);
  var chk = new Date( Day.valueOf() );
  return (chk.getFullYear()==_year && (chk.getMonth()+1)==_month && chk.getDate()==_day);
}
以上

Use Javascript Date() Object to convert date-time info. But JS Date Object didn't have a method to check if the DATE is valid.

.valueOf() and .getTime() can get NaN. But it is only returned when out of DATE-TIME rang.

Date( '2005-02-31' ) will be accepted, but will be converted into '2005-03-03'.

So I can check the _year,_month &_day if the same after Date() converted.