#include stdio.h
站在用户的角度思考问题,与客户深入沟通,找到海宁网站设计与海宁网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站设计制作、网站制作、企业官网、英文网站、手机端网站、网站推广、域名注册、网站空间、企业邮箱。业务覆盖海宁地区。
#include stdlib.h
#include string.h
#include math.h
#include time.h
int get_days(const char* from, const char* to);
time_t convert(int year,int month,int day);
int main()
{
const char* from="2013-3-15";
const char* to="2015-8-14";
int days=get_days(from,to);
printf("From:%s\nTo:%s\n",from,to);
printf("%d\n",days);
return 0;
}
time_t convert(int year,int month,int day)
{
struct tm info={0};
info.tm_year=year-1900;
info.tm_mon=month-1;
info.tm_mday=day;
return mktime(info);
}
int get_days(const char* from, const char* to)
{
int year,month,day,fromSecond,toSecond;
sscanf(from,"%d-%d-%d",year,month,day);
fromSecond=(int)convert(year,month,day);
sscanf(to,"%d-%d-%d",year,month,day);
toSecond=(int)convert(year,month,day);
return (toSecond-fromSecond)/24/3600;
}
From:2013-3-15
To:2015-8-14
882
Press any key to continue
这才算是用了库函数了···
int GetMonthDays(int year,int month)
{
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
break;
case 4:
case 6:
case 9:
case 11:
return 30;
break;
case 2:
if((year%4==0 year%100!=0 ) || (year%400==0))
{
return 29;
}
else
{
return 28;
}
break;
default:
printf("month error!");
return 0;
break;
}
}
1970 年以后的时间,可以用 time.h 里的函数计算。时间精度为秒。按题目要求,输出时间单位用天。程序如下:
#include stdio.h
#include time.h
time_t YMD_hhmmss_2_s70(int Y, int M, int D, int hh, int mm, int ss){
struct tm *target_tm;
time_t tt;
time (tt);
target_tm=localtime(tt);
target_tm-tm_year = Y - 1900;
target_tm-tm_mon= M - 1;
target_tm-tm_mday = D;
target_tm-tm_hour = hh; // hour
target_tm-tm_min = mm;
target_tm-tm_sec = ss;
tt = mktime(target_tm); // from tm to time_t (s)
return tt;
}
int main()
{
int y1,m1,d1,y2,m2,d2;
time_t t1,t2;
int dt;
printf("input y1 m1 d1: ");
scanf("%d %d %d",y1,m1,d1);
printf("\ninput y2 m2 d2: ");
scanf("%d %d %d",y2,m2,d2);
t1 = YMD_hhmmss_2_s70(y1,m1,d1,0,0,0);
t2 = YMD_hhmmss_2_s70(y2,m2,d2,0,0,0);
dt = (t2-t1)/(24*3600);
printf("\ndt=%d\n",dt);
return 0;
}
这里未包含日期的合法性判断。
1970 年以前 要另写程序。某年的日子是当年的第几天可用下面函数得出:
int YMD_2_JD(int Y, int M, int D){
const short MonthDay[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int JD,i;
JD=D;
for (i=0;iM;i++) JD+=MonthDay[i];
if (((Y%4==0)(Y%100!=0)||(Y%400==0)) (M2)) JD++;
return JD;
}
整年的天数,涉及闰年的判断:
某年是否闰年,用 (Y%4==0)(Y%100!=0)||(Y%400==0) 判断。闰年366天,平年365天。 有了这些,写程序不难。
未考虑公元前的年月日计算。