0

我试图在 C 中区分两个日期,但我收到这样的输出:

未来日期:18-11-2013 22:8

当前日期:18-11-2013 22:8

这是我的代码:

#include <stdio.h>
#include <time.h>

int main(int argc, char *argv[])
{   
    // 2 years ahead
    time_t unixtime = time(NULL);
    struct tm *future = localtime(&unixtime);
    future->tm_year += 2;

    // current time
    time_t unixtime_now = time(NULL);
    struct tm *current = localtime(&unixtime_now);

    printf("future date: %d-%d-%d %d:%d\n", future->tm_mday, 1 + future->tm_mon, 1900 + future->tm_year, future->tm_hour, future->tm_min);
    printf("current date: %d-%d-%d %d:%d\n", current->tm_mday, 1 + current->tm_mon, 1900 + current->tm_year, current->tm_hour, current->tm_min);

    return 0;
}
4

2 回答 2

2

那是因为 localtime() 不可重入。

当你这样做

struct tm *future = localtime(&unixtime);
 ... 
struct tm *current = localtime(&unixtime_now);

第一次调用返回一个指向运行时管理的某个静态位置的指针。第二次调用使用相同的位置来存储数据。所以现在两者都future指向current完全相同的东西。

您需要将struct tm您自己管理的存储复制出来:例如

struct tm future = *localtime(&unixtime);
 ... 
struct tm current = *localtime(&unixtime_now);

或者,如果您的平台上可用,则使用更合适localtime_r的功能。

struct tm future;
localtime_r(&unixtime, &future);
 ... 
struct tm current;
localtime_r(&unixtime, &current);
于 2013-11-18T21:15:34.333 回答
2

的返回值localtime是一个指向静态分配结构的指针,该结构可能被进一步调用日期/时间函数覆盖。如果您想将指向的数据保留更长时间,则需要对其进行复制,或使用其他功能,例如localtime_r.

请参阅localtime(3) 手册页

localtime() 函数将日历时间 timep 转换为分解的时间表示,表示相对于用户指定的时区。该函数的行为就好像它调用了 tzset(3) 并使用有关当前时区的信息设置外部变量 tzname,使用协调世界时 (UTC) 和本地标准时间之间的差异(以秒为单位)设置时区,如果是日光,则将日光设置为非零值储蓄时间规则适用于一年中的某些时候。返回值指向一个静态分配的结构,随后调用任何日期和时间函数可能会覆盖该结构。localtime_r() 函数的作用相同,但将数据存储在用户提供的结构中。它不需要设置 tzname、时区和日光。

于 2013-11-18T21:15:38.827 回答