为什么 gettimeofday 时区是错误的? [英] Why is the gettimeofday timezone wrong?

查看:321
本文介绍了为什么 gettimeofday 时区是错误的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 Ubuntu 16 中的当前时区,ftime 和 gettimeofday 都返回 0.时区在 Ubuntu 提供的日期和时间设置中设置正确.没有设置 TZ 环境变量.

Both ftime and gettimeofday are returning 0 for the current timezone in Ubuntu 16. The timezone is set correctly in the date and time settings provided by Ubuntu. There is no TZ env variable set.

我不想只是修复"它,因为这是在许多不同环境中使用的生产软件.所以我只想要一种可靠的方式以编程方式获取时区(最好还有当前的 DST 偏移量).

I don't want to just "fix" it because this is production software used in many different contexts. So I just want a reliable way of programmatically getting the timezone (and preferably the current DST offset as well).

到目前为止我的尝试:

#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' 命令有效:

The 'date' command is working:

matthew@mallen-ubuntu:~$ date +%Z
AEDT
matthew@mallen-ubuntu:~$ date +%z
+1100

我可以生成一个进程来调用date",但是当某些 API 调用可用时,这似乎非常繁重.

I could just spawn a process to call "date", but that seems very heavy handed when some API calls are available.

推荐答案

在 GNU/Linux 上,gettimeofday 的第二个参数非常无用,应该始终为 NULL.gettimeofday 手册页这么说:

On GNU/Linux, the second argument of gettimeofday is quite useless and should always be NULL. The manual page for gettimeofday says this:

时区结构的使用已经过时;tz 参数通常应指定为 NULL.

The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.

即使在非 Linux 系统上,tz_dsttime 也有无用的语义(例如,它报告说印度使用夏令时,因为它在大约 70 年前使用了一段时间).

Even on non-Linux systems, the tz_dsttime has useless semantics (e.g., it reports that India uses DST because it did so for a brief period about seventy years ago).

如果您需要获取当前时间的时区,您需要使用 localtimelocaltime_r 并检查它产生的分解时间结构(而不​​是全局变量,例如 daylight).您可能感兴趣的 struct tm 成员是 tm_isdsttm_gmtofftm_zone.后两个是glibc扩展.

If you need to obtain the time zone for the current time, you need to use localtime or localtime_r and examine the broken-down time structure it produces (and not global variables such as daylight). The struct tm members you are probably interested are tm_isdst, tm_gmtoff, and perhaps tm_zone. The latter two are glibc extensions.

这篇关于为什么 gettimeofday 时区是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆