比较DateTime大小 用C#实现
时间: 2023-04-09 15:03:35 浏览: 181
C#实现验证码Winform
4星 · 用户满意度95%
在C语言中,可以使用time.h头文件中的time_t类型和difftime函数来比较两个DateTime的大小。
具体步骤如下:
1. 将两个DateTime转换为time_t类型,可以使用mktime函数将struct tm类型的时间转换为time_t类型。
2. 使用difftime函数比较两个time_t类型的时间差,如果返回值为正数,则第一个时间较晚;如果返回值为负数,则第二个时间较晚;如果返回值为0,则两个时间相等。
示例代码如下:
```
#include <stdio.h>
#include <time.h>
int main()
{
struct tm time1 = {0};
time1.tm_year = 2021 - 1900;
time1.tm_mon = 8 - 1;
time1.tm_mday = 1;
time1.tm_hour = 12;
time1.tm_min = 0;
time1.tm_sec = 0;
struct tm time2 = {0};
time2.tm_year = 2021 - 1900;
time2.tm_mon = 8 - 1;
time2.tm_mday = 2;
time2.tm_hour = 12;
time2.tm_min = 0;
time2.tm_sec = 0;
time_t t1 = mktime(&time1);
time_t t2 = mktime(&time2);
double diff = difftime(t1, t2);
if (diff > 0)
{
printf("time1 is later than time2\n");
}
else if (diff < 0)
{
printf("time2 is later than time1\n");
}
else
{
printf("time1 and time2 are equal\n");
}
return 0;
}
```
阅读全文