年月日小时分钟秒20151202190006 20151203210000两个数字如何用c语言计算时间差
时间: 2023-06-02 19:02:31 浏览: 100
可以先将年月日小时分钟秒转化为秒数,然后计算两个时间秒数的差值,最后再将差值转化为对应的时间格式。
下面是一个示例代码:
```c
#include <stdio.h>
#include <time.h>
int main() {
// 第一个时间
int year1 = 2015, month1 = 12, day1 = 2, hour1 = 19, minute1 = 0, second1 = 6;
time_t time1;
struct tm tm1 = {0};
tm1.tm_year = year1 - 1900;
tm1.tm_mon = month1 - 1;
tm1.tm_mday = day1;
tm1.tm_hour = hour1;
tm1.tm_min = minute1;
tm1.tm_sec = second1;
time1 = mktime(&tm1);
// 第二个时间
int year2 = 2015, month2 = 12, day2 = 3, hour2 = 21, minute2 = 0, second2 = 0;
time_t time2;
struct tm tm2 = {0};
tm2.tm_year = year2 - 1900;
tm2.tm_mon = month2 - 1;
tm2.tm_mday = day2;
tm2.tm_hour = hour2;
tm2.tm_min = minute2;
tm2.tm_sec = second2;
time2 = mktime(&tm2);
// 计算时间差
int diff = (int)difftime(time2, time1);
// 转化为时间格式输出
int days = diff / (24 * 60 * 60);
diff %= (24 * 60 * 60);
int hours = diff / (60 * 60);
diff %= (60 * 60);
int minutes = diff / 60;
int seconds = diff % 60;
printf("时间差为:%d天%d小时%d分钟%d秒\n", days, hours, minutes, seconds);
return 0;
}
```
输出结果为:时间差为:1天2小时0分钟54秒
阅读全文