JS判断日期格式是否合法的简单实例
js判断日期格式是否合法的简单实例
//函数名:checkdatetime
//功能介绍:检查是否为日期时间
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;
}
/**
判断输入框中输入的日期格式为yyyy-mm-dd和正确的日期
*/
function isdate(sm,mystring) {
var reg = /^(\d{4})-(\d{2})-(\d{2})$/;
var str = mystring;
var arr = reg.exec(str);
if (str=="") return true;
if (!reg.test(str)&®exp.$2<=12&®exp.$3<=31){
alert("请保证"+sm+"中输入的日期格式为yyyy-mm-dd或正确的日期!");
return false;
}
return true;
}
function todatefromstring( strdate )
{
if (strdate.length != 8) {
return null ;
}
var dtdate = null ;
var nyear = parseint( strdate.substring( 0, 4 ), 10 ) ;
var nmonth = parseint( strdate.substring( 4, 6 ), 10 ) ;
var nday = parseint( strdate.substring( 6, 8 ), 10 ) ;
if( isnan( nyear ) == true || isnan( nmonth ) == true || isnan( nday ) == true )
{
return null ;
}
dtdate = new date( nyear, nmonth - 1, nday ) ;
if( nyear != dtdate.getfullyear() || ( nmonth - 1 ) != dtdate.getmonth() || nday != dtdate.getdate() )
{
return null ;
}
return dtdate ;
}
yyyymmdd的格式
上一篇: 寒性体质的女人要听这4句劝