js判斷時間格式是否正確程式碼

antzone發表於2017-03-14

如果要求比較嚴格的話,時間格式也是需要進行判斷的,下面就是一段這樣的程式碼例項,希望能夠給需要的朋友帶來一定的幫助,程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
function isDateString(strDate){ 
  var strSeparator = "-"; 
  var strDateArray; 
  var intYear; 
  var intMonth; 
  var intDay; 
  var boolLeapYear; 
  var ErrorMsg = "";
  strDateArray = strDate.split(strSeparator); 
  if(strDateArray.length != 3) 
  { 
    ErrorMsg += "日期格式必須為: yyyy-MM-dd"; 
    return ErrorMsg; 
  } 
  intYear = parseInt(strDateArray[0],10); 
  intMonth = parseInt(strDateArray[1],10); 
  intDay = parseInt(strDateArray[2],10); 
  if(isNaN(intYear)||isNaN(intMonth)||isNaN(intDay)) 
  { 
    ErrorMsg += "日期格式錯誤: 年月日必須為純數字"; 
    return ErrorMsg; 
  } 
  if(intMonth>12 || intMonth<1) 
  { 
    ErrorMsg += "日期格式錯誤: 月份必須介於1和12之間"; 
    return ErrorMsg; 
  } 
  if((intMonth==1||intMonth==3||intMonth==5||intMonth==7 ||intMonth==8||intMonth==10||intMonth==12)&&(intDay>31||intDay<1)) 
  { 
    ErrorMsg += "日期格式錯誤: 大月的天數必須介於1到31之間"; 
    return ErrorMsg; 
  } 
  if((intMonth==4||intMonth==6||intMonth==9||intMonth==11)&&(intDay>30||intDay<1)) 
  { 
    ErrorMsg += "日期格式錯誤: 小月的天數必須介於1到31之間"; 
    return ErrorMsg; 
  } 
  if(intMonth==2)
  { 
    if(intDay < 1) 
    { 
      ErrorMsg += "日期格式錯誤: 日期必須大於或等於1"; 
      return ErrorMsg; 
    } 
    boolLeapYear = false; 
    if((intYear%100) == 0)
    { 
      if((intYear%400) == 0) 
      boolLeapYear = true; 
    } 
    else
    { 
      if((intYear % 4) == 0) 
      boolLeapYear = true; 
    } 
    if(boolLeapYear)
    { 
      if(intDay > 29) 
      { 
        ErrorMsg += "日期格式錯誤: 閏年的2月份天數不能超過29"; 
        return ErrorMsg; 
      } 
    } 
    else
    { 
      if(intDay > 28) 
      { 
        ErrorMsg += "日期格式錯誤: 非閏年的2月份天數不能超過28"; 
        return ErrorMsg; 
      } 
    } 
  } 
  return ErrorMsg; 
}

相關文章