Home > front end >  localtime() and gmtime() giving exactly the same output
localtime() and gmtime() giving exactly the same output

Time:05-06

ADDENDUM:
I followed the suggestion provided and replaced calls to gmtime and localtime with calls to gmtime_r and localtime_r and everything worked as expected. The updated source code is as follows:

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);
} 

Original Post:

I am making calls to gmtime() and localtime(), passing the same time_t value to both. However, I am getting the same result.
Here is my source code:

#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);
}

The output is as follows. As can be seen, we get the same output in both cases.

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

CodePudding user response:

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

Since you call gmtime, then call localtime, before printing either, you're getting two pointers to the same struct, which only contains the second result. Either print each result immediately after the call, or use localtime_r and gmtime_r with pointers to struct tms that you have allocated yourself.

CodePudding user response:

Two possibilities.

  1. The local time zone of your system currently has an offset of 0.
  2. utcTime and localTime are sharing the same memory.

localtime and gmtime return a pointer to the same struct every time. They may share the same memory. So utcTime and localTime might be the same.

You can check with printf("gm: %p local: %p", utcTime, localTime).

Use localtime_r and gmtime_r to avoid this.

  •  Tags:  
  • c
  • Related