我有以下代码:
int main(void) {
struct tm str_time;
time_t time_of_day;
str_time.tm_year = 2012-1900;
str_time.tm_mon = 6;
str_time.tm_mday = 5;
str_time.tm_hour = 10;
str_time.tm_min = 3;
str_time.tm_sec = 5;
str_time.tm_isdst = 0;
time_of_day = mktime(&str_time);
printf(ctime(&time_of_day));
return 0;
}
它工作得很好,但我找不到一种方法来验证代码中的日期和时间是否与计算机中的日期和时间相同,有没有人知道如何比较两个日期?
最佳答案
... have any idea of how to compare both dates?
OP 正在做 3 件导致潜在时差的事情。
在调用
mktime(&str_time);
之前,代码可能没有填写所有需要的字段。 C 指定至少 9 个字段。最好对str_time
进行零填充,然后设置 7 个字段。这是一个相对罕见的问题。OP 关于日期“2016-06-25 06:58:31”的评论。但不发布用于填充
struct tm
的值。一个常见的错误代码是tm_mon
是自一月以来的月份,因此需要负 1。str_time.tm_year = 2016-1900; str_time.tm_mon = 6 - 1; str_time.tm_mday = 25; str_time.tm_hour = 6; str_time.tm_min = 58; str_time.tm_sec = 31; str_time.tm_isdst = tbd; // see below
str_time.tm_isdst = 0;
将时间戳设置为无夏令时。通常最好使用str_time.tm_isdst = -1;
并让系统确定 DST 是否生效。
与其计算给定用户年-月-日的time_t
,不如使用计算机时间并将其转换为年-月-日,然后进行比较。当然,任何差异/差异都会更容易理解。
将计算机本地年月日与用户输入进行比较
// February 20, 2016
int y = 2016;
int m = 2;
int d = 20;
time_t now;
if (time(&now) == -1) Handle_Error();
struct tm *tm = localtime(&now);
if (tm == NULL) Handle_Error();
if (((tm->tm_year + 1900) == y) && ((tm->tm_mon + 1) == m) && (tm->tm_mday == d)) {
puts("Dates match");
}
关于c - 如何在C中检查日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35530862/