UTC到ANSI C的当天时间?

Bad*_*adr 4 c

如何将utc时间转换为当天的当地时间?

Pat*_*ick 6

您必须将tzset()与time/gmtime/localtime/mktime函数混合使用.

试试这个:

#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;
}
Run Code Online (Sandbox Code Playgroud)

基本上,这个程序将当前计算机日作为GMT(时间(NULL)),并将其转换为CET:

$ ./tolocal 
gmt: Tue Feb 16 09:37:30 2010
cet: Tue Feb 16 08:37:30 2010
Run Code Online (Sandbox Code Playgroud)