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?
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);