【问题标题】:How can I set the time zone before calling strftime?如何在调用 strftime 之前设置时区?
【发布时间】:2009-10-25 06:41:48
【问题描述】:

我使用自 1970 年以来的秒(和微秒)以及时区和 dst 标志来表示日期。我想使用 strftime 打印日期的表示,但它使用从环境中获取的时区(extern long int timezone)的全局值。如何让 strftime 打印我选择的区域?

【问题讨论】:

    标签: c unix


    【解决方案1】:

    以下程序将 UNIX 环境变量 TZ 设置为您所需的时区,然后使用 strftime 打印格式化时间。

    在下面的示例中,时区设置为美国太平洋时区。

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main (int argc, char *argv[])
    {
        struct tm *mt;
        time_t mtt;
        char ftime[10];
    
        setenv("TZ", "PST8PDT", 1);
        tzset();
        mtt = time(NULL);
        mt = localtime(&mtt);
        strftime(ftime,sizeof(ftime),"%Z %H%M",mt);
    
        printf("%s\n", ftime);
    }
    

    【讨论】:

      【解决方案2】:

      通过设置timezone 全局变量更改时区,并使用localtime 获取您通过strftime 打印的时间。

      【讨论】:

        猜你喜欢
        • 2014-11-16
        • 2016-06-25
        • 2013-05-19
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        相关资源
        最近更新 更多