#include?stdio.h
站在用戶的角度思考問題,與客戶深入溝通,找到海寧網(wǎng)站設(shè)計(jì)與海寧網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗(yàn)好的作品,建站類型包括:網(wǎng)站設(shè)計(jì)制作、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、域名注冊、網(wǎng)站空間、企業(yè)郵箱。業(yè)務(wù)覆蓋海寧地區(qū)。
#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
這才算是用了庫函數(shù)了···
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 里的函數(shù)計(jì)算。時間精度為秒。按題目要求,輸出時間單位用天。程序如下:
#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 年以前 要另寫程序。某年的日子是當(dāng)年的第幾天可用下面函數(shù)得出:
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;
}
整年的天數(shù),涉及閏年的判斷:
某年是否閏年,用 (Y%4==0)(Y%100!=0)||(Y%400==0) 判斷。閏年366天,平年365天。 有了這些,寫程序不難。
未考慮公元前的年月日計(jì)算。