‘localtime()’ loves ‘05:30:00’

Updated: May 07, 2024

Got some problem when I’m converting elapsed time time_t to struct tm for printing time in %H:%M:%S format. Here is the code,

/* code to learn how 'localtime()' works */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char **argv)
{
     struct tm time1;
     struct tm *time2;
     time_t time;
     char timestring[20];

     time2 = (struct tm *)malloc(sizeof(struct tm));

     /* setting 0 seconds to time */
     time = (time_t) 0;
     localtime_r(&time, &time1);

     time1.tm_hour = time1.tm_hour - 5;
     time1.tm_min = time1.tm_min - 30;

     strftime(timestring,
             20,
             "%H:%M:%S",
             &time1);
     printf("Time1: %s\n",
             timestring);

     /* setting 1 minute 10 seconds to time */
     time = (time_t) 70;
     time2 = localtime(&time);

     time2->tm_hour = time2->tm_hour - 5;
     time2->tm_min = time2->tm_min - 30;

     strftime(timestring,
             20,
             "%H:%M:%S",
             time2);
     printf("Time2: %s\n",
             timestring);

     free(time2);
     return(0);
}

And the output is,

Time1: 05:30:00
Time2: 05:31:10

I don’t know why its happening, localtime() creates struct tm structure which by default have 05:30:00 as its starting time. I need to manually subtract the 5 from tm_hour and 3 from tm_min to get what I want.

time1.tm_hour = time1.tm_hour - 5;
time1.tm_min = time1.tm_min - 30;

time2->tm_hour = time2->tm_hour - 5;
time2->tm_min = time2->tm_min - 30;

Here is the updated output,

Time1: 00:00:00
Time2: 00:01:10

Also localtime() sets default values to all the variables in the result struct tm structure. google not helping to find the reason.