Home > Web Front-end > JS Tutorial > js method to determine date and time validity_javascript skills

js method to determine date and time validity_javascript skills

WBOY
Release: 2016-05-16 15:35:21
Original
1681 people have browsed it

Share two methods of using javascript to verify whether the date and time are valid
First type:

//| 日期有效性验证 
//| 格式为:YYYY-MM-DD或YYYY/MM/DD  
function IsValidDate(DateStr){ 
  var sDate=DateStr.replace(/(^\s+|\s+$)/g,'');//去两边空格; 
  if(sDate==''){ 
    return true; 
  } 
  //如果格式满足YYYY-(/)MM-(/)DD或YYYY-(/)M-(/)DD或YYYY-(/)M-(/)D或YYYY-(/)MM-(/)D就替换为'' 
  //数据库中,合法日期可以是:YYYY-MM/DD(2003-3/21),数据库会自动转换为YYYY-MM-DD格式 
  var s=sDate.replace(/[\d]{ 4,4 }[\-/]{1}[\d]{1,2}[\-/]{1}[\d]{1,2}/g,''); 
  if(s==''){//说明格式满足YYYY-MM-DD或YYYY-M-DD或YYYY-M-D或YYYY-MM-D 
    var t=new Date(sDate.replace(/\-/g,'/')); 
    var ar=sDate.split(/[-/:]/); 
    if(ar[0]!=t.getYear()||ar[1]!=t.getMonth()+1||ar[2]!=t.getDate()){//alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。'); 
      return false; 
    } 
  }else{//alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。'); 
    return false; 
  } 
  return true; 
} 
Copy after login

Second type:

//| 日期时间有效性检查 
//| 格式为:YYYY-MM-DD HH:MM:SS 
function CheckDateTime(str){ 
  var reg=/^(\d+)-(\d{ 1,2})-(\d{ 1,2})(\d{ 1,2}):(\d{1,2}):(\d{1,2})$/; 
  var r=str.match(reg); 
  if(r==null) return false; 
  r[2]=r[2]-1; 
  var d= new Date(r[1],r[2],r[3],r[4],r[5],r[6]); 
  if(d.getFullYear()!=r[1]) return false; 
  if(d.getMonth()!=r[2]) return false; 
  if(d.getDate()!=r[3]) return false; 
  if(d.getHours()!=r[4]) return false; 
  if(d.getMinutes()!=r[5]) return false; 
  if(d.getSeconds()!=r[6]) return false; 
  return true; 
} 
Copy after login

The above two methods are shared with everyone, I hope you can like them.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template