1

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
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
DontPanic
  • 2,164
  • 5
  • 29
  • 56
  • Which OS? Post a complete, minimal program and the output of running both `date` (on Linux or similar for other OS) and your program in the same shell session. Also, print `tm_hour`. – rveerd Nov 06 '20 at 07:31
  • @rveerd: 'date' reported 10:20 AM – DontPanic Nov 06 '20 at 15:29
  • I found that if I *do* specify TZ in environment (e.g. TZ=EST), localtime works Ok, even though doc says that if it's not defined, it will determined from the OS. I hesitated to do this because I didn't want (possibly clueless) users to need to do this. Also I guess that I'll have to change it to EDT every summer. – DontPanic Nov 06 '20 at 21:07
  • Can't reproduce this on Linux, so it seems to be a Windows-specific issue. If your program does not need to be portable, you can consider using a Windows-specific API, such as [GetLocalTime()](https://learn.microsoft.com/en-us/windows/win32/sysinfo/local-time). – rveerd Nov 09 '20 at 08:35

2 Answers2

0

My guess is that you're using an uninitialized value in the time funciton and not capturing its return value.

Try this:

   time_t ltime;
   struct tm *tm;
   ltime = time( NULL );
   tm = localtime( &ltime );
Kieveli
  • 10,944
  • 6
  • 56
  • 81
  • I say uninitialized, but it would be 0... 0 is different from NULL as a parameter to the time() function. – Kieveli Nov 05 '20 at 15:27
0

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".

DontPanic
  • 2,164
  • 5
  • 29
  • 56