JS判断日期格式是否合法的简单实例
类似于PHP中的Checkdate。
//函数名:CheckDateTime
//功能介绍:检查是否为日期时间
functionCheckDateTime(str){
varreg=/^(\d+)-(\d{1,2})-(\d{1,2})(\d{1,2}):(\d{1,2}):(\d{1,2})$/;
varr=str.match(reg);
if(r==null)returnfalse;
r[2]=r[2]-1;
vard=newDate(r[1],r[2],r[3],r[4],r[5],r[6]);
if(d.getFullYear()!=r[1])returnfalse;
if(d.getMonth()!=r[2])returnfalse;
if(d.getDate()!=r[3])returnfalse;
if(d.getHours()!=r[4])returnfalse;
if(d.getMinutes()!=r[5])returnfalse;
if(d.getSeconds()!=r[6])returnfalse;
returntrue;
}
/**
判断输入框中输入的日期格式为yyyy-mm-dd和正确的日期
*/
functionIsDate(sm,mystring){
varreg=/^(\d{4})-(\d{2})-(\d{2})$/;
varstr=mystring;
vararr=reg.exec(str);
if(str=="")returntrue;
if(!reg.test(str)&&RegExp.$2<=12&&RegExp.$3<=31){
alert("请保证"+sm+"中输入的日期格式为yyyy-mm-dd或正确的日期!");
returnfalse;
}
returntrue;
}
functiontoDateFromString(strDate)
{
if(strDate.length!=8){
returnnull;
}
vardtDate=null;
varnYear=parseInt(strDate.substring(0,4),10);
varnMonth=parseInt(strDate.substring(4,6),10);
varnDay=parseInt(strDate.substring(6,8),10);
if(isNaN(nYear)==true||isNaN(nMonth)==true||isNaN(nDay)==true)
{
returnnull;
}
dtDate=newDate(nYear,nMonth-1,nDay);
if(nYear!=dtDate.getFullYear()||(nMonth-1)!=dtDate.getMonth()||nDay!=dtDate.getDate())
{
returnnull;
}
returndtDate;
}
YYYYMMDD的格式
以上这篇JS判断日期格式是否合法的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。