js 中的日期操作

來源:互聯網
上載者:User

1 判斷日期是否正確。

//日付タイプチェック
function isStrDate(strDateObj) {
 var strDate = strDateObj.value;
 var wDate;
 var adays;
 
 if (strDate == '') {
  return true;
 }
 
 var aMatch1 = /^/d{8}$/;
 var aMatch2 = /^(/d{4})(-){1}(/d{2})(-){1}(/d{2})|(/d{4})(//){1}(/d{2})(//){1}(/d{2})$/;
 if (!aMatch1.test(strDate) && !aMatch2.test(strDate)){
  alert(errors_format_data);
  strDateObj.focus();
  return false;
 }
 try{
  if (strDate.indexOf('-') != -1) {
   strDate = strDate.replace(new RegExp('-', "g"),'/');
  } else if (strDate.indexOf('/') == -1) {
   strDate = strDate.substr(0,4)+'/'+strDate.substr(4,2)+'/'+strDate.substr(6,2);
  }
  wDate = new Date(strDate);// 這是為從設日期,如:strDate = 2007/12/35,那麼 wDate = 2008/01/04。
 }catch(e){
  alert(errors_format_data);
  strDateObj.focus();
  return false;
 }
 adays = strDate.split('/');
 
 if (adays[0].substr(0,2) == '19') { // 這是因為當年份< 2000 是,wDate.getYear()  的結果是四位年份的後兩位,    如,1987,則wDate.getYear()   = 87 。
  adays[0] = parseInt(adays[0].substr(2,2));
 }
 if(wDate.getYear() != adays[0] || wDate.getMonth()+1 != adays[1] || wDate.getDate() != adays[2]){
  strDateObj.focus();
  return false ;
 }
 strDateObj.value = strDate;
 return true;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.