zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JavaScript判断日期格式是否正确的实现代码

JavaScript日期代码 实现 正确 判断 是否 格式
2023-06-13 09:14:29 时间
转载者最起码注明作者和出处!http://www.cnblogs.com/GuominQiu
复制代码代码如下:

//---------------------------------------------------------------------------
//判断日期格式是否正确
//返回值是错误信息,无错误信息即表示合法日期字符串
functionisDateString(strDate){
varstrSeparator="-";//日期分隔符
varstrDateArray;
varintYear;
varintMonth;
varintDay;
varboolLeapYear;
varErrorMsg="";//出错信息
strDateArray=strDate.split(strSeparator);
//没有判断长度,其实2008-8-8也是合理的//strDate.length!=10||
if(strDateArray.length!=3){
ErrorMsg+="日期格式必须为:yyyy-MM-dd";
returnErrorMsg;
}
intYear=parseInt(strDateArray[0],10);
intMonth=parseInt(strDateArray[1],10);
intDay=parseInt(strDateArray[2],10);
if(isNaN(intYear)||isNaN(intMonth)||isNaN(intDay)){
ErrorMsg+="日期格式错误:年月日必须为纯数字";
returnErrorMsg;
}
if(intMonth>12||intMonth<1){
ErrorMsg+="日期格式错误:月份必须介于1和12之间";
returnErrorMsg;
}
if((intMonth==1||intMonth==3||intMonth==5||intMonth==7
||intMonth==8||intMonth==10||intMonth==12)
&&(intDay>31||intDay<1)){
ErrorMsg+="日期格式错误:大月的天数必须介于1到31之间";
returnErrorMsg;
}
if((intMonth==4||intMonth==6||intMonth==9||intMonth==11)
&&(intDay>30||intDay<1)){
ErrorMsg+="日期格式错误:小月的天数必须介于1到31之间";
returnErrorMsg;
}
if(intMonth==2){
if(intDay<1){
ErrorMsg+="日期格式错误:日期必须大于或等于1";
returnErrorMsg;
}
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";
returnErrorMsg;
}
}else{
if(intDay>28){
ErrorMsg+="日期格式错误:非闰年的2月份天数不能超过28";
returnErrorMsg;
}
}
}
returnErrorMsg;
}