首页 > 解决方案 > 如何在 C 中获取当前时间与时区更改的匹配

问题描述

我正在开发基于 Linux 的路由器。我正在开发一个 C 应用程序。我想在我的应用程序中连续获取当前时间。

问题是,尽管我在应用程序启动后更改了时区,但它根据应用程序启动时区给了我时间。系统的时区已更改。Linux 终端上的date命令显示不同的时区和日期/时间。

time_t currTm;
struct tm *loctime;
char udrTime[50];
while (1)
{
    currTm = time(NULL);
    loctime = localtime(&currTm);
    strftime(udrTime, sizeof(udrTime), "%Y-%m-%d %H:%M:%S", loctime);
    printf("udr_time = %s\n", udrTime);
    usleep(10000);
}  

我希望输出根据时区变化。

标签: clinux

解决方案


要从应用程序中更改时区,只需设置TZ环境变量,不需要其他任何东西:

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

void print_time(time_t t) {
    char buf[256];
    strftime(buf, sizeof buf, "%H:%M:%S", localtime(&t));
    printf("%s %s\n", getenv("TZ"), buf);
}

int main() {
    time_t t = time(NULL);

    setenv("TZ", "Europe/London", 1);
    print_time(t);

    setenv("TZ", "America/New_York", 1);
    print_time(t);

    return 0;
}

输出:

Europe/London 15:48:58
America/New_York 10:48:58

推荐阅读