下面算“今天”是第幾天。
如果要算某天,你只要輸出年月日,再調YMD_hhmmss_2_s70 得 time_t 值(代替 now) 就可以了。方法同生日轉bt.
# include
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;
}
main()
{
int b_year,b_month,b_day;
time_t bt, now;
long double dif;
int d;
now = time(NULL);
printf("input b_year, month,day\n");
scanf("%d %d %d",&b_year,&b_month,&b_day);
bt = YMD_hhmmss_2_s70( b_year,b_month,b_day, 0, 0, 1);
dif = difftime (now,bt);
d = (int) (dif / 86400.0);
printf("days: %d\n",d);
==
時間函式運用方法
下面算“今天”是第幾天。
如果要算某天,你只要輸出年月日,再調YMD_hhmmss_2_s70 得 time_t 值(代替 now) 就可以了。方法同生日轉bt.
# include
# include
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;
}
main()
{
int b_year,b_month,b_day;
time_t bt, now;
long double dif;
int d;
now = time(NULL);
printf("input b_year, month,day\n");
scanf("%d %d %d",&b_year,&b_month,&b_day);
bt = YMD_hhmmss_2_s70( b_year,b_month,b_day, 0, 0, 1);
dif = difftime (now,bt);
d = (int) (dif / 86400.0);
printf("days: %d\n",d);
}
==
時間函式運用方法