功能:输入起始日期,输入终止日期,得出总共天数(按银行业的算头不算尾方式)
比如起始日期为 20050101 , 终止日期为 20050110 , 计算得到 9 天
运行环境:Red Hat Enterprise Linux AS release 3 、AIX Version 5 操作系统上测试通过
编译命令:cc -o asima asima.c
执行命令:./asima
源代码:
main()
{
int days; /*define int type to save the days result*/
char b_date[30]; /*define char type to save the start date*/
char e_date[30]; /*define char type to save the end date*/
printf("put in the start date:");
scanf("%8s",b_date); /*put the start date,format as YYYYMMDD*/
printf("put in the end date:");
scanf("%8s",e_date); /*put the end date,format as YYYYMMDD*/
days=diff_days(&b_date,&e_date); /*call function diff_days to calculate*/
printf("days: %d/n",days); /*put the result on the screen*/
}
/********************************************************************
Function: diff_days
Description: calculate days for from the start date to end date
Calls: net()
Called By: main()
Input: char *date1 - the start date
char *date2 - the end date
Output: no Output parameter
Return: -1 - has error occur
numberic - the result for days
Others:
**********************************************************************/
diff_days(char * date1, char * date2)
{
int days1;
int days2;
days1 = net(date1,1);
days2 = net(date2,1);
if ( -1 == days1 || -1 == days2 || days1 > days2 )
{
return(-1);
}
else
{
return(days2 - days1);
}
}
int net(char *date,int status)
{
int yr_days[2][14] ={0, 0, 31, 59, 90,120,151,181,212,243,273,304,334,365,
0, 0, 31, 60, 91,121,152,182,213,244,274,305,335,366 };
int yr,mon,day;
int leap;
int leapday, netdays;
if ( -1 == chkdate(date) )
{
printf("pls. put in the availability date/n");
return(-1);
}
sscanf(date,"%4d %2d %2d",&yr,&mon,&day); /*convert date to numeric*/
leap = (yr%4==0 && yr%100!=0 || yr%400==0); /*check leap year */
if ( 0 == status ) /*return net days of the year */
{
netdays = yr_days[leap][mon] + day;
}
else /*return net days from 1900/01/01*/
{
yr -= 1900;
leapday = yr / 4.01;
netdays = yr*365 + leapday + yr_days[leap][mon] + day;
}
return(netdays);
}
int chkdate(char *date)
{
int day_tbl[2][13] ={ 0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
0,31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int yr,mon,day;
int leap,i;
for( i=0; i<8; i++ )
{
if( (date[i]<'0') || (date[i]>'9') )
{
return(-1);
}
}
if (sscanf(date, "%4d %2d %2d", &yr, &mon, &day) != 3)
{
return(-1);
}
if (mon < 1 || mon > 12 || day < 1 || day > 31)
{
return(-1);
}
leap = (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0); /* leap year */
if (day > day_tbl[leap][mon])
{
return(-1);
}
else
{
return(0);
}
}