1

This simple C code compiles without errors in both MS Visual Studio/Windows 11 and GCC/Linux.

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <time.h>

int main() {
    struct tm ed_bday = {
        .tm_year = 56,
        .tm_mon = 7,
        .tm_mday = 10,
        .tm_hour = 0,
        .tm_min = 0,
        .tm_sec = 0,
        .tm_isdst = 0,
    };
    time_t ed_time_epoch;
    ed_time_epoch = mktime(&ed_bday);
    printf("Ed was born %s\n", ctime(&ed_time_epoch));

    return 0;
}

However the output differs. On MSVS it outputs:

Ed was born (null)

On GCC it outputs:

Ed was born Fri Aug 10 01:00:00 1956

I know MS prefers localtime_s(), but according to their own documentation there is the option of staying with localtime() so long as you add #define _CRT_SECURE_NO_WARNINGS 1. This does not seem to be the case

tadman
  • 208,517
  • 23
  • 234
  • 262
Dabbo
  • 143
  • 5
  • 3
    Start by isolating the issue to either `mktime` or `ctime` – Eugene Sh. Jun 09 '23 at 20:31
  • 1
    *I know MS prefers localtime_s()* Of course they do - the [MS version of `localtime_s()`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-s-localtime32-s-localtime64-s?view=msvc-170) is different from the [standard C version in Annex K](https://port70.net/~nsz/c/c11/n1570.html#K.3.8.2.4) – Andrew Henle Jun 09 '23 at 20:37
  • 1
    What's the value in `ed_time_epoch`? You can print it with something like `printf( "ed_time_epoch: %lld\n", ( long long ) ed_time_epoch );` – Andrew Henle Jun 09 '23 at 20:44
  • Hi Andrew: On GCC/Linux I get ed_time_epoch: -422668800, whereas on MS Visual Studio I get ed_time_epoch: -1 – Dabbo Jun 09 '23 at 21:05
  • btw, I casted to an int rather than long long – Dabbo Jun 09 '23 at 21:07
  • 4
    This is documented https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/mktime-mktime32-mktime64?view=msvc-170. "If timeptr references a date before midnight, January 1, 1970, or if the calendar time can't be represented, _mktime32 returns -1 cast to type time_t." – patthoyts Jun 09 '23 at 21:14
  • 2
    @patthoyts that's in the C standard too: *The `mktime` function returns the specified calendar time encoded as a value of `typetime_t`. If the calendar time cannot be represented, the function returns the value `(time_t)(−1)`.* – Weather Vane Jun 09 '23 at 21:26
  • How to handle dates before 1 Jan 1970, please? – Dabbo Jun 09 '23 at 21:27
  • 2
    Please see [Date handling before 1970 c++](https://stackoverflow.com/questions/21859147/date-handling-before-1970-c) perhaps similar for C. Or search for "c stackoverflow dates before 1970 -c++". – Weather Vane Jun 09 '23 at 21:36

0 Answers0