c - 如何在 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);
}
我希望输出根据时区变化。
解决方案
要从应用程序中更改时区,只需设置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
推荐阅读
- google-analytics - 除了 Google Tag Manager 之外,还执行 Google Analytics Functions
- mysql - 无法使用 dropwizard 和 mysql docker 容器迁移数据库
- graphql - 错误:不变违规:gatsby-source-graphql 需要指定选项“typeName”
- python - 在类之间共享属性:这里是多继承权和“pythonic”吗?
- php - 为什么第一个 php 文件返回错误信息,而第二个返回正确信息?
- laravel - ReflectionException : 类 env 不存在。难道我做错了什么?
- c# - 将 JSON 数据插入到动态中的字段(例如联系人中的名字)中
- c++ - 如何解决没有上下文类型信息错误的重载函数?
- html - 谷歌浏览器不显示数据列表标签
- python - 如何从浏览器测试中检索 Ping 下载和上传时间?