8

在 C 中,是否有一种简单的跨平台方法来检索给定时区开始和结束夏令时的日期?

我已经有了时区偏移信息以及当前是否正在观察夏令时,但我确实需要夏令时开始和结束的日期(对于我无法控制的外部依赖)。在 Windows 中,我使用GetTimeZoneInformation来获取TimeZoneInfo,但我找不到适用于 Linux/Solaris/Mac 的类似功能。我还应该指出,我不能仅仅依靠美国的夏令时采用规则,因为我无法预测它将在哪些国家/地区使用。

我知道获取此信息的唯一方法是通过zdump或直接查看 /usr/share/lib/zoneinfo 文件本身,但我希望有更好的解决方案。

感谢您的任何帮助,您可以提供。

4

4 回答 4

5

The portable and consistent way to deal with this is to build a year-round TZ offset table (for each day in the current year in the current timezone) at application startup. Resolve each day's midnight local time to UTC (GMT), and record the effective timezone offset vis-a-vis UTC (GMT) for the day in question. Look for transitions in the effective TZ offsets year-round (transitions will indicate DST changes.) This approach is consistent and portable in that only depends on localtime/gmtime functioning reliably on the platform in question, and will return results fully consistent with localtime/gmtime calls. However, it becomes a bit more complicated if you require DST information for other timezones (than the process' default timezone.)

You can also directly use the TZ/Olson database (code available for both *nix and Windows), for maximum flexibility, but unless the underlying runtime/OS use the exact same timezone information (and your application uses TZ/Olson timezone information and gmtime/localtime interchangeably) then you're in for unpleasant surprises.

于 2009-03-24T18:10:12.990 回答
2

I'm not sure there's a good cross-platform way to do this, but there is a programmatic interface to the /usr/share/zoneinfo files (or at least a description of the format) in tzfile.h, (available on Mac OS X and Linux).

Windows uses slightly different mappings from tzinfo, but there's a conversion table you could use to generify your interface between Windows and Unix.

于 2009-03-24T17:57:03.973 回答
1

在 C 中,是否有一种简单的跨平台方法来检索给定时区 > 开始和结束夏令时的日期?

不。

我在 90 年代后期在 VMS 上为 DEC 实现了 TZ 支持。

首先,没有跨平台的解决方案。

其次,日期每年都不同,也因立法而异。事实上,没有完全可靠的程序化解决方案。

于 2009-03-24T22:01:21.313 回答
0

如果您需要 C++(不是 C),请查看 boost::date_time 库http://www.boost.org/doc/libs/1_38_0/doc/html/date_time.html

于 2009-08-13T05:30:46.697 回答