我试图在控制台中以本地时区(-0600)打印当前时间,然后以+0100时区打印时间。目前,我正在使用gmtime,并将1添加到tm_hour部分。

但是,当使用strftime时,它仍然打印:“ ... +0000”。

如何正确打印?例如,如何更改我的有效时区?

最佳答案

在具有GCC 6.3.0的macOS Sierra 10.12.2上,以下代码有效:

#include "posixver.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#ifndef lint

extern const char jlss_id_settz_c[];
const char jlss_id_settz_c[] = "@(#)$Id: settz.c,v 1.2 2017/01/23 07:06:21 jleffler Exp $";
#endif

static void time_convert(time_t t0, char const *tz_value)
{
    char old_tz[64] = "-none-";
    char *tz = getenv("TZ");
    if (tz != 0)
        strcpy(old_tz, tz);
    setenv("TZ", tz_value, 1);
    tzset();
    char new_tz[64];
    strcpy(new_tz, getenv("TZ"));
    char buffer[64];
    struct tm *lt = localtime(&t0);
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", lt);
    if (strcmp(old_tz, "-none-") == 0)
        unsetenv("TZ");
    else
        setenv("TZ", old_tz, 1);
    tzset();
    printf("%ld = %s (TZ=%s)\n", (long)t0, buffer, new_tz);
}

int main(void)
{
    time_t t0 = time(0);
    char *tz = getenv("TZ");
    if (tz != 0)
        time_convert(t0, tz);
    time_convert(t0, "UTC0");
    time_convert(t0, "IST-5:30");
    time_convert(t0, "EST5");
    time_convert(t0, "EST5EDT");
    time_convert(t0, "PST8");
    time_convert(t0, "PST8PDT");
}


默认情况下,在环境中未设置TZ -必须对那些getenv("TZ")返回NULL的测试进行麻烦的处理。运行时,输出为:

$ ./settz
1485155290 = 2017-01-23 07:08:10 (TZ=UTC0)
1485155290 = 2017-01-23 12:38:10 (TZ=IST-5:30)
1485155290 = 2017-01-23 02:08:10 (TZ=EST5)
1485155290 = 2017-01-23 02:08:10 (TZ=EST5EDT)
1485155290 = 2017-01-22 23:08:10 (TZ=PST8)
1485155290 = 2017-01-22 23:08:10 (TZ=PST8PDT)
$


将环境设置为TZ=US/Alaska时,输出为:

$ TZ=US/Alaska ./settz
1485155395 = 2017-01-22 22:09:55 (TZ=US/Alaska)
1485155395 = 2017-01-23 07:09:55 (TZ=UTC0)
1485155395 = 2017-01-23 12:39:55 (TZ=IST-5:30)
1485155395 = 2017-01-23 02:09:55 (TZ=EST5)
1485155395 = 2017-01-23 02:09:55 (TZ=EST5EDT)
1485155395 = 2017-01-22 23:09:55 (TZ=PST8)
1485155395 = 2017-01-22 23:09:55 (TZ=PST8PDT)
$


这是一种丑陋的技术。它也不快。但是,在某些平台上,它确实可以工作。

关于c - 在C中的不同时区打印当前时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41799800/

10-11 22:35
查看更多