• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

奋斗中...

曾经的程序员。ASP.NET/C#, JavaScript, PL/SQL, T-SQL; 工具: VS2003/2005, Oracle, SQLServer; 偶尔写点CSS, 批处理.
头脑中经常有新想法, 可惜没有去实现.
Never give up.
Never get into a fight with a pig. Both of you will get dirty. But the pig actually enjoys it.
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

[JavaScript]JavaScript判断日期格式是否正确

修改自http://blog.csdn.net/dallasnash/archive/2007/04/18/1569068.aspx

没有多大变动,主要是返回错误信息,以便调用函数部分可以alert出来。据说可以用正则表达式校验,下次再研究下。

转载者最起码注明作者和出处!http://www.cnblogs.com/GuominQiu

//---------------------------------------------------------------------------
//
判断日期格式是否正确
//
返回值是错误信息, 无错误信息即表示合法日期字符串
function isDateString(strDate){
var strSeparator = "-"; //日期分隔符
var strDateArray;
var intYear;
var intMonth;
var intDay;
var boolLeapYear;
var ErrorMsg = ""; //出错信息
strDateArray = strDate.split(strSeparator);

//没有判断长度,其实2008-8-8也是合理的//strDate.length != 10 ||
if(strDateArray.length != 3) {
ErrorMsg
+= "日期格式必须为: yyyy-MM-dd";
return ErrorMsg;
}

intYear
= parseInt(strDateArray[0],10);
intMonth
= parseInt(strDateArray[1],10);
intDay
= parseInt(strDateArray[2],10);

if(isNaN(intYear)||isNaN(intMonth)||isNaN(intDay)) {
ErrorMsg
+= "日期格式错误: 年月日必须为纯数字";
return ErrorMsg;
}

if(intMonth>12 || intMonth<1) {
ErrorMsg
+= "日期格式错误: 月份必须介于1和12之间";
return ErrorMsg;
}

if((intMonth==1||intMonth==3||intMonth==5||intMonth==7
||intMonth==8||intMonth==10||intMonth==12)
&&(intDay>31||intDay<1)) {
ErrorMsg
+= "日期格式错误: 大月的天数必须介于1到31之间";
return ErrorMsg;
}

if((intMonth==4||intMonth==6||intMonth==9||intMonth==11)
&&(intDay>30||intDay<1)) {
ErrorMsg
+= "日期格式错误: 小月的天数必须介于1到31之间";
return ErrorMsg;
}

if(intMonth==2){
if(intDay < 1) {
ErrorMsg
+= "日期格式错误: 日期必须大于或等于1";
return ErrorMsg;
}

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";
return ErrorMsg;
}
}
else {
if(intDay > 28) {
ErrorMsg
+= "日期格式错误: 非闰年的2月份天数不能超过28";
return ErrorMsg;
}
}
}

return ErrorMsg;
}

posted on 2011-07-01 16:53  jes  阅读(1423)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3