Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two different times in C

I am trying to write a program in C to display current time in two time zones :Greenich Mean Time and Indian Std. Time. IST is 5hr 30min ahead of GMT. That is equal to 19800 seconds.
My code is …..

#include <stdio.h>
#include <time.h>
int main()

{
    time_t gmt, ist; // gmt for Greenich Mean Time and ist for Indian Standard Time
    struct tm *gmt_tmp, *ist_tmp;
    char sgmt [100], sist [100];
    
    time (&gmt);
    ist = gmt + 19800; // to account for 5hr 30min time difference
    printf("gmt = %ld\n",gmt);
    printf("ist = %ld\n",ist);
    
    gmt_tmp = localtime (&gmt);
    ist_tmp = localtime (&ist);
    
    printf("gmt hour = %d\n",gmt_tmp->tm_hour);
    printf("ist hour = %d\n",ist_tmp->tm_hour);
    
    strftime (sgmt, 99, "%A, %d %B %Y, %X", gmt_tmp);
    strftime (sist, 99, "%A, %d %B %Y, %X", ist_tmp);
    
    printf("Current Greenwich Mean Time:       %s\n", sgmt);
    printf("Current Indian Standard Time:      %s\n", sist);

    return 0;
}

The output is:

gmt = 1735909933
ist = 1735929733
gmt hour = 18
ist hour = 18
Current Greenwich Mean Time:       Friday, 03 January 2025, 18:42:13
Current Indian Standard Time:      Friday, 03 January 2025, 18:42:13

The output shows indian time for both, GMT and IST.I cant understand why the GMT variables get overwritten when IST variables are calculated. Am I missing something here?
How could I rectify this?
Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The localtime function returns a pointer to static data. So when you call it twice, it’s returning the same pointer value, and the results of the second call overwrite the results of the first call.

You should instead use localtime_r, which accepts an additional parameter of type struct tm * where the result is stored.

struct tm gmt_tmp, ist_tmp;
...
localtime_r(&gmt, &gmt_tmp);
localtime_r(&ist, &ist_tmp);
...
strftime (sgmt, 99, "%A, %d %B %Y, %X", &gmt_tmp);
strftime (sist, 99, "%A, %d %B %Y, %X", &ist_tmp);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading