c语言判断日期是否合法的函数(改进版)

来源:互联网 发布:浙江省进出口贸易数据 编辑:程序博客网 时间:2024/05/14 07:09

主要包括小于1900和大于2056年都属于不合法的日期

 另外对于润年要判断2月份是28天还是29天.


short int Date(const char * strDate)

{
char strYear[5],strMonth[3],strDay[3];
int iYear=0,iMonth=0,iDay=0;

memset(strYear,0,sizeof(strYear));
memset(strMonth,0,sizeof(strMonth));
memset(strDay,0,sizeof(strDay));

if(strDate==NULL) 
{
return 0;
}

if(strlen(strDate)!=8) 
{
return 0;
}

if(isN(strDate)==-1) 
{
return 0;
}

memcpy(strYear,strDate,4);
memcpy(strMonth,strDate+4,2);
memcpy(strDay,strDate+4+2,2);

iYear=atoi(strYear);
iMonth=atoi(strMonth);
iDay=atoi(strDay);

if((iYear<1900) || (iYear>2056)) 
{
return 0;
}

if(iMonth<1 || iMonth>12) 
{
return 0;
}

switch(iMonth)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(iDay<1 || iDay>31) 
{
return 0;
}
break;
case 4: case 6: case 9: case 11:
if(iDay<1 || iDay>30) 
{
return 0;
}
break;
case 2:
  if(iYear % 4 ==0 && iYear % 100 !=0 || iYear % 400 ==0)/*是闰年*/
  {
  if(iDay<1 || iDay>29) 
  {
  return 0;
  }
  }
  else
  {
    if(iDay<1 || iDay>28) 
    {
    return 0;     
    }
  }
break;
}
return 1;
}
0 0