为什么 gettimeofday 时区错误?
Why is the gettimeofday timezone wrong?
对于 Ubuntu 16 中的当前时区,ftime 和 gettimeofday 都返回 0。在 Ubuntu 提供的日期和时间设置中正确设置了时区。没有设置 TZ 环境变量。
我不想只是 "fix" 因为这是在许多不同环境中使用的生产软件。所以我只想要一种可靠的方式来以编程方式获取时区(最好还有当前的 DST 偏移量)。
我目前的尝试:
#if 0
timeb tbTime;
ftime(&tbTime);
int CurTz = -tbTime.timezone;
#else
struct timeval tv;
struct timezone tz;
int r = gettimeofday(&tv, &tz);
if (r)
return NO_ZONE;
int CurTz = tz.tz_minuteswest;
#endif
'date' 命令正在运行:
matthew@mallen-ubuntu:~$ date +%Z
AEDT
matthew@mallen-ubuntu:~$ date +%z
+1100
我可以生成一个进程来调用 "date",但是当某些 API 调用可用时,这似乎非常繁重。
在 GNU/Linux 上,gettimeofday
的第二个参数非常无用,应该始终是 NULL
。 manual page for gettimeofday
表示:
The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.
即使在非Linux 系统上,tz_dsttime
也有无用的语义(例如,它报告说印度使用夏令时是因为它在大约七十年前的一段短暂时间里这样做了)。
如果你需要获取当前时间的时区,你需要使用localtime
或localtime_r
并检查它产生的分解时间结构(而不是全局变量,如daylight
)。您可能感兴趣的 struct tm
成员是 tm_isdst
、tm_gmtoff
,也许还有 tm_zone
。后两个是glibc扩展。
对于 Ubuntu 16 中的当前时区,ftime 和 gettimeofday 都返回 0。在 Ubuntu 提供的日期和时间设置中正确设置了时区。没有设置 TZ 环境变量。
我不想只是 "fix" 因为这是在许多不同环境中使用的生产软件。所以我只想要一种可靠的方式来以编程方式获取时区(最好还有当前的 DST 偏移量)。
我目前的尝试:
#if 0
timeb tbTime;
ftime(&tbTime);
int CurTz = -tbTime.timezone;
#else
struct timeval tv;
struct timezone tz;
int r = gettimeofday(&tv, &tz);
if (r)
return NO_ZONE;
int CurTz = tz.tz_minuteswest;
#endif
'date' 命令正在运行:
matthew@mallen-ubuntu:~$ date +%Z
AEDT
matthew@mallen-ubuntu:~$ date +%z
+1100
我可以生成一个进程来调用 "date",但是当某些 API 调用可用时,这似乎非常繁重。
在 GNU/Linux 上,gettimeofday
的第二个参数非常无用,应该始终是 NULL
。 manual page for gettimeofday
表示:
The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.
即使在非Linux 系统上,tz_dsttime
也有无用的语义(例如,它报告说印度使用夏令时是因为它在大约七十年前的一段短暂时间里这样做了)。
如果你需要获取当前时间的时区,你需要使用localtime
或localtime_r
并检查它产生的分解时间结构(而不是全局变量,如daylight
)。您可能感兴趣的 struct tm
成员是 tm_isdst
、tm_gmtoff
,也许还有 tm_zone
。后两个是glibc扩展。