C代码手动设置两个年月日时间,燃尽计算这两个时间相差的天数
时间: 2024-10-13 17:19:15 浏览: 51
在C语言中,你可以使用`struct tm`结构手动设置日期,并通过`mktime()`将其转换为时间戳,再利用`difftime()`函数计算两个时间戳之间的差值,进而得到天数。以下是手动设置并计算两个日期之间天数的一个简单示例:
```c
#include <stdio.h>
#include <time.h>
// 定义结构体表示日期
typedef struct {
int year;
int month;
int day;
} Date;
// 求两个日期之间的天数差
int days_between(Date date1, Date date2) {
struct tm t1, t2;
// 将日期1设置到tm结构体
t1.tm_year = date1.year - 1900; // 时间库以1900为起点
t1.tm_mon = date1.month - 1; // 月份从0开始计数
t1.tm_mday = date1.day;
// 将日期2设置到tm结构体
t2.tm_year = date2.year - 1900;
t2.tm_mon = date2.month - 1;
t2.tm_mday = date2.day;
// 转换为时间戳并计算差值
time_t t_time1 = mktime(&t1);
time_t t_time2 = mktime(&t2);
double diff_seconds = difftime(t_time2, t_time1);
return static_cast<int>(diff_seconds / (60 * 60 * 24)); // 返回天数差
}
int main() {
Date date1 = {2020, 1, 1}; // 示例日期1
Date date2 = {2022, 12, 31}; // 示例日期2
int days_diff = days_between(date1, date2);
printf("The difference in days between %d-%02d-%02d and %d-%02d-%02d is: %d\n",
date1.year, date1.month, date1.day, date2.year, date2.month, date2.day, days_diff);
return 0;
}
```
阅读全文
相关推荐














