c - 如何在C中检查日期时间

标签 c

我有以下代码:

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 件导致潜在时差的事情。

  1. 在调用 mktime(&str_time); 之前,代码可能没有填写所有需要的字段。 C 指定至少 9 个字段。最好对 str_time 进行零填充,然后设置 7 个字段。这是一个相对罕见的问题。

  2. 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
    
  3. 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/

相关文章:

c - 结构内部消失后的段错误(变量已损坏)

TensorFlow 中 C 代码的代码完成

c - 检查输入字符串是整数还是 float 的函数?

c - strcmp 比较两个字符串时 word[0] 是什么意思

c - 可以在'printf'函数中使用'&'吗?

尝试从服务器 tcp 读回时客户端挂起

c - 表达式必须有指针类型错误

即使未使用数组,定义空数组是否会导致未定义的行为?

无法写入 dsPIC30F OSCCON

c - 如何在不为函数指针使用 typedef 的情况下声明函数指针数组?