JavaScript 判斷輸入的日期是否是合法日期的兩種方法

來源:互聯網
上載者:User

JavaScript 代碼
/// 檢查輸入的日期是否是一個正確的日期格式:
/// 支援 yyyy-M-d、yyyy-MM-dd、yyyy/M/d、yyyy/MM/dd 四種輸入格式。

function checkDate(strInputDate) {
  // 定義一個月份天數常量數組
  var DA = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  // 統一日期格式
  strDate = strInputDate.replace(/-/g, "/");

  //判斷日期是否是預期的格式
  if (strDate.indexOf("/") == -1) {
    alert("請輸入 yyyy-M-d、yyyy-MM-dd、yyyy/M/d、yyyy/MM/dd 格式。")
    return false;
  }

  // 分解出年月日
  arrD = strDate.split("/");
  if (arrD.length != 3) return false;
  y = parseInt(arrD[0], 10);
  m = parseInt(arrD[1], 10);
  d = parseInt(arrD[2], 10);

  //判斷年月日是否是數字
  if (isNaN(y) || isNaN(m) || isNaN(d)) return false;

  // 判斷月份是否在1-12之間
  if (m > 12 || m < 1) return false;
  //判斷是否是閏年
  if (isLoopYear(y)) DA[2] = 29;

  //判斷輸入的日是否超過了當月月份的總天數。
  if (d > DA[m]) return false;

  //各種條件都驗證了,則應該是一個合法的日期了。
  // 如果要對日期進行一次格式化,則可以在這裡進行處理了,下面格式化成資料庫識別的日期格式 yyyy-MM-dd
  // str = y + "-" + (m<10?"0":"") + m + "-" + (d<10?"0":"") + d;
  str = y + "-" + (m < 10 ? "0" : "") + m + "-" + (d < 10 ? "0" : "") + d;
  alert(str)
  return true;
}
function isLoopYear(theYear) {
  return (new Date(theYear, 1, 29).getDate() == 29);
}

//方法二:
/// 檢查輸入的日期是否是一個正確的日期格式:
/// 支援 yyyy-M-d、yyyy-MM-dd、yyyy/M/d、yyyy/MM/dd 四種輸入格式。
function CheckDate2(strInputDate) {
  if (strInputDate == "") return false;
  strInputDate = strInputDate.replace(/-/g, "/");
  var d = new Date(strInputDate);
  if (isNaN(d)) return false;
  var arr = strInputDate.split("/");
  return ((parseInt(arr[0], 10) == d.getFullYear()) && (parseInt(arr[1], 10) == (d.getMonth() + 1)) && (parseInt(arr[2], 10) == d.getDate()));
}
 

 

作者:孟憲會

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.