Search code examples
cdstlocaltime

localtime() reports incorrect hour and isdst flag


UPDATED CODE 11/06/20

localtime is reporting incorrect tm_hour (+1 hour) and tm_isdst (1).

Notes:

  1. I am in the Eastern time zone.
  2. It is currently Nov 6 (not DST).
  3. Environment variable TZ is not set.
  4. The Control Panel (Date & Time) is set to "(UTC-05:00) Eastern Time (US & Canada)".

There were many SO posts about this issue but none directly addressed this issue.

Is this a bug or am I doing something wrong?

My code is below (compiled with MSVC "Win32 Debug", run on Win10-64):

//  localtime.c - Test Program for localtime()

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

    int
    main(int argc,char **argv)
    {
        time_t utc;
        struct tm *tm;
    
        utc = time( NULL );
        tm = localtime( &utc );
    
        printf( "Program localtime.exe:\n" );
        printf( "Env Var TZ: %s\n", getenv( "TZ" ) );
        printf( "tm->tm_hour:  %d\n", tm->tm_hour  );
        printf( "tm->tm_isdst: %d\n", tm->tm_isdst );
    
        printf( "Press any key to exit...\n" );
        getch();
        exit( 0 );
        return( 0 );
    }     

Program Output (run at 10:20 AM EST)

Program localtime.exe:
Env Var TZ: (null)
tm->tm_hour:  11
tm->tm_isdst: 1

Solution

  • Very, very weird. If find if I set env var "TZ", localtime() works fine. What is Strange is, it makes no difference what I set it to, e.g. "XXX".