Home > Web Front-end > JS Tutorial > body text

js判断日期时间有效性的方法_javascript技巧

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

分享两种使用javascript验证日期以及时间是否有效的方法
第一种:

//| 日期有效性验证 
//| 格式为: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

第二种:

//| 日期时间有效性检查 
//| 格式为: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

以上这两种方法分享给大家,希望大家可以喜欢。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!