Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTC to Time of the day in ANSI C?

Tags:

c

how to convert the utc time to local time of the day?

like image 829
Badr Avatar asked Jan 22 '23 13:01

Badr


1 Answers

You must use a mix of tzset() with time/gmtime/localtime/mktime functions.

Try this:

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

#include <time.h>

time_t makelocal(struct tm *tm, char *zone)
{
    time_t ret;
    char *tz;

    tz = getenv("TZ");
    setenv("TZ", zone, 1);
    tzset();
    ret = mktime(tm);
    if(tz)
        setenv("TZ", tz, 1);
    else
        unsetenv("TZ");
    tzset();
    return ret;
}

int main(void)
{
    time_t gmt_time;
    time_t local_time;
    struct tm *gmt_tm;

    gmt_time = time(NULL);
    gmt_tm = gmtime(&gmt_time);
    local_time = makelocal(gmt_tm, "CET");

    printf("gmt: %s", ctime(&gmt_time));
    printf("cet: %s", ctime(&local_time));

    return 0;
}

Basically, this program takes the current computer day as GMT (time(NULL)), and convert it to CET:

$ ./tolocal 
gmt: Tue Feb 16 09:37:30 2010
cet: Tue Feb 16 08:37:30 2010
like image 62
Patrick Avatar answered Feb 03 '23 13:02

Patrick