Kirubakaran
Kirubakaran

Reputation: 398

Convert the time string of UTC to IST time in C language

I am looking for the UTC (from RFC3339 format) to IST conversion in C program. But I could not find any generic way to convert the time.

Here, I found the shell script to convert the UTC time (in RFC3339 format) to IST and I am trying to implement in C code.

From the script, I can't find the equivalent way for the statement newdate=$(TZ=IST date -d "$formatT UTC-5:30") in C code.

So, I did time diff of -5:30 with the GMT time as shown in below snippet. But, it is not working as expected.

int main(int argc, char *argv[])
{  
    const char *utctime = "2019-07-24T11:47:33";
    struct tm tm = {0};
    char s[128] = {0};

    if (NULL == (strptime(utctime, "%Y-%m-%dT%H:%M:%S", &tm))) {
        printf("strptime failed\n");
    }

    printf("IST Time : %2d:%02d\n", ((tm.tm_hour-5)%24), tm.tm_min-30);

}

Kindly, guide me to do the task in C code that the script does.

Upvotes: 1

Views: 3615

Answers (1)

Aconcagua
Aconcagua

Reputation: 25536

Non-portable, linux:

struct tm time;
// fill appropriately

time_t utc = timegm(&time)

localtime_r(&utc, &time);

If your local time zone isn't IST, you need to change to before calling local time:

setenv("TZ", "IST-05:30:00", 1);
//             ^ not entirely sure if this is correct, please verify yourself (*)

tzset();

Edit (following the comments): (*) Especially if daylight saving time (DST) has to be applied, the time zone string looks different; you find information about at tzset documentation. Possibly the server provides time zone information in a local file, then you might try :Asia/Kolkata as well.

You might retrieve current timezone with getenv first if you intend to restore it afterwards, complete example is shown at timegm documentation.

The portable way would now be to first set timezone to UTC, call mktime instead of timegm, then set timezone to IST and call localtime just as in non-portable version and finally restore local timezone (if intended/needed and you haven't already done so by setting it to IST).

Upvotes: 2

Related Questions