
程序代码:
#include <stdio.h>
#include <time.h>
#include <math.h>
int seconds_to_current( double* delta, int year, int mon, int day, int hour, int min, int sec )
{
struct tm t;
t.tm_year = year-1900;
t.tm_mon = mon-1;
t.tm_mday = day;
t.tm_hour = hour;
t.tm_min = min;
t.tm_sec = sec;
time_t time_beg = mktime(&t);
if( time_beg == (time_t)(-1) )
return -1;
time_t time_end = time(NULL);
if( time_end == (time_t)(-1) )
return -2;
*delta = difftime( time_end, time_beg );
return 0;
}
void foo( int year, int mon, int day )
{
double delta;
int r = seconds_to_current( &delta, year, mon, day, 0, 0, 0 );
if( r == -1 )
printf( "%04d-%02d-%02d 不在 time_t 的表达范围之内.\n", year, mon, day );
else if( r == -2 )
printf( "当前日历时间 不在 time_t 的表达范围之内.\n" );
else
{
double seconds = round( fabs(delta) ); // 四舍五入到整数秒
long hms = lround( fmod(seconds, 24*60*60) );
double days = round( (seconds-hms)/(24.*60*60) ); // 天数
long hour_ = hms/3600;
long min_ = hms%3600/60;
long sec_ = hms%60;
printf( "%s %.f天%ld时%ld分%ld秒\n", (delta<0?"未来":"迄今"), days, hour_, min_, sec_ );
}
}
int main( void )
{
foo( 2021, 10, 29 );
foo( 2022, 10, 28 );
foo( 2022, 10, 29 );
foo( 2022, 10, 30 );
foo( 2023, 10, 29 );
}
输出
迄今 365天17时20分42秒
迄今 1天17时20分42秒
迄今 0天17时20分42秒
未来 0天6时39分18秒
未来 364天6时39分18秒