当前位置:三九宝宝网 → 宝宝教育 → 教学论文 → 正文

c语言如何计算两个时间相差多少

更新:01-07 整理:39baobao.com
字体:

主要可以通过两种方法实现,第一种直接计算,第二种通过difftime

函数实现,具体代码如下,

//函数功能计算两个时间差,未考虑时间数据有效性

#include #include #include #include int main(int argc, char *argv[]) { struct time1{ int hour; int minute; int second; }; struct time1 t1,t2; struct tm *ptr1,*ptr2; time_t lt; time(<;);//当前系统时间 ptr1=localtime(<;);//返回指向当前时间的指针 ptr2=(struct tm *)malloc(sizeof(struct tm));//动态申请指针ptr2 memcpy(ptr2,ptr1,sizeof(struct tm));//复制ptr1 long diff=0;//存储时间差 //第一种方法,直接计算 printf("please input the structure time1:"); scanf("%d %d %d",&t1.hour,&t1.minute,&t1.second); printf("please input the structure time2:"); scanf("%d %d %d",&t2.hour,&t2.minute,&t2.second); printf("t1=%d:%d:%d,t2=%d:%d:%d\n",t1.hour,t1.minute,t1.second,t2.hour,t2.minute,t2.second); diff=(t1.hour*3600+t1.minute*60+t1.second)-(t2.hour*3600+t2.minute*60+t2.second); diff=(diff>0)?diff:(-1*diff); printf("1. diff=%ld\n",diff); //第二种方法,通过difftime计算 ptr1->tm_sec=t1.second;//更改当前时间为t1,struct tm结构其他成员不变 ptr1->tm_min=t1.minute; ptr1->tm_hour=t1.hour; ptr2->tm_sec=t2.second;//更改当前时间为t2 ptr2->tm_min=t2.minute; ptr2->tm_hour=t2.hour; diff=(long)difftime(mktime(ptr2),mktime(ptr1)); printf("2. diff=%ld\n",diff); return 0; } double difftime( time_t time2, time_t time1 );函数返回时间参数time2和time1之差的秒数表示。 结构体tm定义如下, struct tm { int tm_sec; /* 秒–取值区间为[0,59] */ int tm_min; /* 分 - 取值区间为[0,59] */ int tm_hour; /* 时 - 取值区间为[0,23] */ int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */ int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */ int tm_year; /* 年份,其值从1900开始 */ int tm_wday; /* 星期–取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */ int tm_yday; /* 从每年的1月1日开始的天数–取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */ int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/ long int tm_gmtoff; /*指定了日期变更线东面时区中UTC东部时区正秒数或UTC西部时区的负秒数*/ const char *tm_zone; /*当前时区的名字(与环境变量TZ有关)*/ };

本文地址:https://www.39baobao.com/show/29_26260.html

以上内容来自互联网,请自行判断内容的正确性。若本站收录的信息无意侵犯了贵司版权,请联系我们,我们会及时处理和回复,谢谢.