localtime() 和 gmtime() 给出完全相同的输出

localtime() and gmtime() giving exactly the same output

附录:
我跟随 并将对 gmtimelocaltime 的调用替换为对 gmtime_rlocaltime_r 的调用,一切都按预期进行。更新后的源码如下:

int main()
{
    time_t tmi;
    time(&tmi);
    struct tm utcTime, localTime;
    gmtime_r(&tmi, &utcTime);
    localtime_r(&tmi, &localTime);
    
    displayStructTm(&utcTime, "UTC");
    displayStructTm(&localTime, "Local Time");

    return (0);
} 

原文Post:

我正在调用 gmtime()localtime(),将相同的 time_t 值传递给两者。但是,我得到了相同的结果。
这是我的源代码:

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

void displayStructTm(const struct tm* tmPtr, const char*label) {
    printf("\n%s\n", label);
    printf("tm_sec: %d\n", tmPtr->tm_sec);
    printf("tm_hour: %d\n", tmPtr->tm_hour);
    printf("tm_min: %d\n", tmPtr->tm_min);
    printf("tm_mday: %d\n", tmPtr->tm_mday);
    printf("tm_mon: %d\n", tmPtr->tm_mon);
    printf("tm_year: %d\n", tmPtr->tm_year);
    printf("tm_wday: %d\n", tmPtr->tm_wday);
    printf("tm_yday: %d\n", tmPtr->tm_yday);
    printf("tm_isdst: %d\n", tmPtr->tm_isdst);
}

int main()
{
    time_t tmi;
    time(&tmi);
    struct tm* utcTime = gmtime(&tmi);
    struct tm* localTime = localtime(&tmi);
    
    displayStructTm(utcTime, "UTC");
    displayStructTm(localTime, "Local Time");

    return (0);
}

输出结果如下。 可以看出,我们在两种情况下得到相同的输出。

UTC
tm_sec: 27
tm_hour: 3
tm_min: 21
tm_mday: 6
tm_mon: 4
tm_year: 122
tm_wday: 5
tm_yday: 125
tm_isdst: 0

Local Time
tm_sec: 27
tm_hour: 3
tm_min: 21
tm_mday: 6
tm_mon: 4
tm_year: 122
tm_wday: 5
tm_yday: 125
tm_isdst: 0

The return value points to a statically-allocated struct which might be overwritten by subsequent calls to any of the date and time functions. The localtime_r() function does the same, but stores the data in a user-supplied struct.

man localtime

由于您先调用 gmtime,然后调用 localtime,然后再打印其中任何一个,您会得到两个指向同一结构的指针,该结构仅包含第二个结果。要么在调用后立即打印每个结果,要么使用 localtime_rgmtime_r 以及指向您自己分配的 struct tm 的指针。

两种可能性。

  1. 您系统的本地时区当前偏移量为 0。
  2. utcTimelocalTime 共享同一内存。

localtimegmtime return 每次都指向相同结构的指针。他们可能共享相同的内存。所以 utcTimelocalTime 可能是一样的。

您可以通过 printf("gm: %p local: %p", utcTime, localTime) 查看。

使用 localtime_rgmtime_r 来避免这种情况。