【问题标题】:How to get current time match with timezone changes in C如何在 C 中获取当前时间与时区更改的匹配
【发布时间】:2019-06-21 13:07:27
【问题描述】:

我正在开发基于 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);
}  

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

【问题讨论】:

  • 您的系统上是否设置了TZ 环境变量?如果是,请在启动 C 应用程序之前尝试取消设置。
  • 我不相信这在标准 C 中是可能的。您可能不得不依赖操作系统特定的 API。
  • 在 Linux 中可能是 tzset(3)tzset 是一个标准的 Posix 函数。另请参阅 How to get the current time zone?What are the disadvantages to using ctime's tzset? 等问题
  • @jww 你错过了这个函数被依赖于时区的其他时间转换函数自动调用。 tzset更新tznametimezone和@987654333 @ 全局变量,通常不直接使用。调用时的条件为tzname != getenv("TZ")
  • 谢谢@Maxim。我在 Posix 规范中找不到该文本。我确实看到 tzset 似乎不是线程安全的,这对我来说有点不寻常。

标签: c linux


【解决方案1】:

要在应用程序中更改时区,只需设置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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多