0

我正在尝试使用 C 获取当前时间time_t current_time = time(NULL)。据我了解,它将返回系统的当前时间。我稍后尝试使用 struct 将其转换为 GMT 时间tm* gmt = gmtime(&current_time)

ctime()我使用和asctime()功能打印两次。

我系统上的当前时间是 GMT + 1。但gmtime()返回的时间与原样相同current_time。我不明白为什么要gmtime()同时返回我。任何帮助将不胜感激。

好的,这里是代码和输出:windows 显示的当前时间是 17:54(斯德哥尔摩区;GMT+1)。我想在 15 点 54 分给我一些东西。或者也许我的理解是错误的......

time_t current_time = time(NULL);

struct tm* gmt = gmtime(&current_time);
struct tm* loc = localtime(&current_time);

printf("current time: %s\n", ctime(&current_time));
printf("gmt time %s\n", asctime(gmt));
printf("local time %s\n", asctime(loc));

输出:

current time: Mon Oct  8 17:54:06 2012

gmt time Mon Oct  8 17:54:06 2012

local time Mon Oct  8 17:54:06 2012

接受的解决方案: 来自 Simes

那可能是你的问题。检查 TZ 环境变量的值;如果不存在,它将默认为 GMT。Cygwin 不会自动从 Windows 获取时区设置。另请参阅本地时间返回 GMT 以了解在 cygwin shell 上运行的 Windows 程序

4

3 回答 3

1

time()返回自纪元以来的秒数。等于 UTC(又名 GMT)

纪元是 1.1.1970, 00:00:00 在英国格林威治。

所以实际上time()返回的不是时间,而是时间

于 2012-10-08T15:49:11.803 回答
1

time_t 类型保存一个值,该值表示自 UNIX 纪元以来的秒数。tm 类型保存一个日历值。

gmtime() 只是将系统时间(始终为 UTC)从 time_t 转换为 tm。这就是为什么值是相同的。如果您想要表示您的本地时间 (GMT+1),这就是 localtime() 的用途。

于 2012-10-08T15:49:36.723 回答
0

在这两行上运行调试器:

struct tm* gmt = gmtime(&current_time);

struct tm* loc = localtime(&current_time);

在第二行中断,观察 gmt 的成员,当你执行第二行时——你会看到一些 gmt 成员改变了值。显然,库使用了一些静态内存。所以在运行第二个语句之前保存第一个语句的结果

于 2017-06-05T22:40:14.403 回答