Tuesday, March 15, 2022

[SOLVED] C compare time_t parameter in func to current time

Issue

Goal:

I'm trying to write a function that accepts a time_t as a parameter and returns a different formatted string by comparing with current time. The data being passed into a function is specifically a st_atim.tv_sec.

Code:

const char *format_time(time_t then)
{
    static char buf[200];
    struct tm *then_tm;
    struct tm *now_tm;
    time_t now;

    now = time(NULL);
    then_tm = localtime(&then);
    now_tm = localtime(&now);
    
    /* blah blah blah comparisons */
    /* shortened code below */
    strftime(buf, sizeof(buf), "%c", then_tm);

    return buf;
}

Problem:

then_tm and now_tm both have the tm form of the parameter now.

If I swap these two lines around...

then_tm = localtime(&then);
now_tm = localtime(&now);
now_tm = localtime(&now);
then_tm = localtime(&then);

... then they both have the tm form of the parameter then.

then_tm should be different to now_tm.

Misc:

  • I am writing a curses file manager as practice.
  • GCC
  • Linux

Solution

(credit to @SteveSummit)

The localtime function has a limitation in that it always returns a pointer to a single, static result buffer

I have refactored my code to use localtime_r like so:

const char *format_time(time_t then)
{
    static char buf[200];
    struct tm then_tm;
    struct tm now_tm;
    time_t now;

    now = time(NULL);
    localtime_r(&then, &then_tm);
    localtime_r(&now, &now_tm);
    
    strftime(buf, sizeof(buf), "%c", &then_tm);
    
    return buf;
}


Answered By - vqmbnklq
Answer Checked By - David Goodson (WPSolving Volunteer)