tags:

views:

93

answers:

1

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

+4  A: 

Hi,

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
Patrick MARIE