- 论坛徽章:
- 0
|
哪位大侠有标准C计算天数的函数?
我编写有计算天数函数,不过传入参数不是字符行是tm结构类型,可以利用这个.o中的StoDate(char *trdt)转换出tm结构指针。
示例:
struct tm *StoDate(char *trdt)
{
struct tm *t;
time_t now;
int i_year,i_mm,i_dd;
char s_year[5];
char s_mm[3];
char s_dd[3];
time(&now);
t=localtime(&now);
memcpy(s_year,trdt,4);
s_year[4]=0;
i_year=atoi(s_year);
memcpy(s_mm,trdt+4,2);
s_mm[2]=0;
i_mm=atoi(s_mm);
memcpy(s_dd,trdt+6,2);
s_dd[2]=0;
i_dd=atoi(s_dd);
/****校验日期***/
switch(i_mm)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(i_dd>;31 || i_dd<1) return NULL;
break;
case 4:
case 6:
case 9:
case 11:
if(i_dd>;30 || i_dd<1) return NULL;
break;
case 2:
if((i_year % 400 == 0) || ((i_year % 4 == 0) && (i_year % 100 !=0)))
{
if(i_dd>;29 && i_dd <0) return NULL;
}
else
{
if(i_dd<0 && i_dd>;2 return NULL;
}
break;
default:
return NULL;
break;
}
t->;tm_year=i_year-1900;
i_mm--; /***月份是0--11***/
t->;tm_mday=i_dd;
t->;tm_mon=i_mm;
t->;tm_hour=0;
t->;tm_min=0;
t->;tm_sec=0;
if(mktime(t) == (time_t)-1) return NULL;
#ifdef DEBUG
printf("wday=[%d]\n",t->;tm_wday);
printf("yday=[%d]\n",t->;tm_yday);
printf("isdst=[%d]\n",t->;tm_isdst);
printf("tm_tzadj=[%ld]\n",t->;tm_tzadj);
printf("tm_name=[%s]\n",t->;tm_name);
#endif
return t;
}
time_t DateDiff(struct tm *val1,struct tm *val2)
{
time_t t1;
time_t t2;
val1->;tm_hour=val2->;tm_hour;
val1->;tm_sec=val2->;tm_sec;
val1->;tm_min=val2->;tm_min;
if((t1=mktime(val1)) == (time_t)-1) return -1;
if((t2=mktime(val2)) == (time_t)-1) return -1;
t1=(t1-t2)/DAY_HOUR;
t1=abs(t1);
return t1;
}
void main()
{
struct tm *dt1,*dt2;
time_t diff_dt;
dt1=StoDate("20030101" ;
dt2=StoDate("20020601" ;
diff_dt=DateDiff(dt1,dt2);
printf("20030101"与"20020601"相距%d天\n" ;fflush(stdout);
return;
} |
|