【发布时间】:2021-02-18 07:53:21
【问题描述】:
更新代码 11/06/20
localtime 报告的 tm_hour(+1 小时)和 tm_isdst (1) 不正确。
注意事项:
- 我在东部时区。
- 目前是 11 月 6 日(不是 DST)。
- 环境变量 TZ 未设置。
- 控制面板(日期和时间)设置为“(UTC-05:00) 东部时间(美国和加拿大)”。
有很多关于这个问题的 SO 帖子,但没有一个直接解决这个问题。
这是一个错误还是我做错了什么?
我的代码如下(用MSVC“Win32 Debug”编译,在Win10-64上运行):
// localtime.c - Test Program for localtime()
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
int
main(int argc,char **argv)
{
time_t utc;
struct tm *tm;
utc = time( NULL );
tm = localtime( &utc );
printf( "Program localtime.exe:\n" );
printf( "Env Var TZ: %s\n", getenv( "TZ" ) );
printf( "tm->tm_hour: %d\n", tm->tm_hour );
printf( "tm->tm_isdst: %d\n", tm->tm_isdst );
printf( "Press any key to exit...\n" );
getch();
exit( 0 );
return( 0 );
}
程序输出(美国东部标准时间上午 10:20 运行)
Program localtime.exe:
Env Var TZ: (null)
tm->tm_hour: 11
tm->tm_isdst: 1
【问题讨论】:
-
哪个操作系统?发布一个完整的、最小的程序以及在同一个 shell 会话中运行
date(在 Linux 或类似的其他操作系统上)和您的程序的输出。另外,打印tm_hour。 -
@rveerd:“日期”报告时间为上午 10:20
-
我发现如果我在环境中做指定 TZ(例如 TZ=EST),localtime 工作正常,即使 doc 说如果它没有定义,它会从操作系统。我犹豫要不要这样做,因为我不希望(可能毫无头绪)用户需要这样做。另外我想我每年夏天都得把它改成 EDT。
-
无法在 Linux 上重现此问题,因此这似乎是特定于 Windows 的问题。如果您的程序不需要可移植,您可以考虑使用特定于 Windows 的 API,例如 GetLocalTime()。