如何在 boost c++ 中获取我的 linux 服务器的当前时间并将其转换为给定的时区(例如 MST-7)? 我希望自动计算夏令时。
如果我运行以下代码,则不考虑 dst:
boost::posix_time::ptime currentTime = boost::posix_time::second_clock::local_time();
date today = day_clock::local_day();
time_zone_ptr phx_tz(new posix_time_zone("MST-07:00:00"));
local_date_time phx_departure(currentTime, phx_tz);
最佳答案
这个问题的真正答案是:不要。
我将引用我在 Daylight saving time and time zone best practices 中的回答:
- If using C++, be sure to use a library that uses the properly implements the IANA timezone database. These include cctz, ICU, and Howard Hinnant's "tz" library.
- Do not use Boost for time zone conversions. While its API claims to support standard IANA (aka "zoneinfo") identifiers, it crudely maps them to fixed offsets without considering the rich history of changes each zone may have had. (Also, the file has fallen out of maintenance.)
考虑到对 Boost 时区文件的最后一次提交日期是 2011 年 6 月 24 日,因此即使他们拥有设计糟糕的 API 和实现,它甚至无法实现自己的 promise ,因为它没有任何了解过去 5 年的时区变化!
此外,您真的不应该使用 POSIX 时区。他们有许多不足,应该被劝阻。请参阅 the timezone tag wiki 中关于 POSIX 时区的部分.相反,您应该使用正确的 IANA/Olson 时区标识符,即 America/Denver
代表美国山区时区(带夏令时),或者 America/Phoenix
代表不使用 DST 的亚利桑那州部分地区。
关于c++ - 使用 dst with boost 将当前服务器时间转换为时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34629227/