-1

When I try to comapre 2 time_t values I get unexplained behavour

time_t t = 12345;
time_t T = 67890;
struct tm *tm = localtime(&t);
struct tm *Tm = localtime(&T);
char timeStamp[40];
sprintf(timeStamp, "(1) %04d-%02d-%02d %02d:%02d:%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
Serial.println(timeStamp);
sprintf(timeStamp, "(2) %04d-%02d-%02d %02d:%02d:%02d", Tm->tm_year + 1900, Tm->tm_mon + 1, Tm->tm_mday, Tm->tm_hour, Tm->tm_min, Tm->tm_sec);
Serial.println(timeStamp);

I get the exact same date.

When commenting out one of each set, I get the correct answer for each one.

Workaround I did was, but i'm sure there is an elegant way to overcome:

        time_t t = 12345;
        time_t T = 12345;
        struct tm *tm = localtime(&t);
        uint8_t now_month = tm->tm_mon;
        uint8_t now_day = tm->tm_mday;
    struct tm *Tm = localtime(&T);
    uint8_t save_month = Tm->tm_mon;
    uint8_t save_day = Tm->tm_mday;

    if (now_month == save_month && now_day == save_day)
    {
    }

guyd
  • 1,033
  • 2
  • 16
  • 51

1 Answers1

1

From the manual page of localtime() (emphasis mine):

The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.

As a solution, I suggest you take a copy of the struct tm used by localtime() to store its result, rather than keeping a pointer to it:

struct tm tm = *localtime(&t);
struct tm Tm = *localtime(&T);
Edgar Bonet
  • 43,033
  • 4
  • 38
  • 76
  • Well somehow I missed that line when seeking the answer. I can't see how they managed to pull such bad design (or it has a reason for that).... I have a shocked look as in your user's pic :) TNX! – guyd Mar 07 '23 at 17:39
  • 1
    @guyd it is the C language old time API – Juraj Mar 07 '23 at 19:18