c++ - 将 local_date_time CET boost 为 UTC

标签 c++ boost timezone

我尝试将 boost local_date_time 转换为 UTC,但我对 utc_time() 的返回时间感到困惑。这是一个简化的代码:

#include "boost/date_time/local_time/local_time.hpp"

int main()
{
  using namespace boost::gregorian;
  using namespace boost::local_time;
  using namespace boost::posix_time;

  ptime dt = ptime(date(2015, Mar, 2), hours(0));
  time_zone_ptr tz_cet(new boost::local_time::posix_time_zone("CET"));
  local_date_time local_dt = boost::local_time::local_date_time(dt, tz_cet);

  std::cout << local_dt << std::endl;
  std::cout << local_dt.utc_time() << std::endl;

  time_zone_ptr tz_utc(new boost::local_time::posix_time_zone("UTC"));
  std::cout << local_dt.local_time_in(tz_utc) << std::endl;
}

输出:

2015-Mar-02 00:00:00 CET
2015-Mar-02 00:00:00
2015-Mar-02 00:00:00 UTC

UTC 应比 CET(欧洲中部时间)晚 1 小时。

这是一个错误还是我遗漏了什么?

最佳答案

boost::local_time::posix_time_zone("CET") 构造函数调用创建了一个带 CET 缩写的区域,并缺少有关与 UTC 的偏移量、时间偏移的信息DST 等,即调用 boost::local_time::posix_time_zone("CET")boost::local_time::posix_time_zone("UTC") 仅在TZ缩写名称,其余同。 coliru code演示它。两个 TZ 的 base_utc_offset 方法调用返回 00:00:00

要解决此问题,必须设置 CET 区域的时间参数,例如“CET+01:00:00”或使用 tz_database类从 CSV 文件加载时区。

以下代码是原始修改后的代码,演示了如何解决问题。请注意,CET 时区描述并不完整,仅作为示例提供。

#include "boost/date_time/local_time/local_time.hpp"
#include <iostream>

int main()
{
    using namespace boost::gregorian;
    using namespace boost::local_time;
    using namespace boost::posix_time;

    ptime dt = ptime(date(2015, Mar, 2), hours(0));
    time_zone_ptr tz_cet(new boost::local_time::posix_time_zone("CET+01:00:00"));
    local_date_time local_dt = boost::local_time::local_date_time(dt, tz_cet);

    std::cout << local_dt << std::endl;
    std::cout << local_dt.utc_time() << std::endl;

    time_zone_ptr tz_utc(new boost::local_time::posix_time_zone("UTC"));
    std::cout << local_dt.local_time_in(tz_utc) << std::endl;
}

coliru 上的相同代码可通过 this 获得链接。

关于c++ - 将 local_date_time CET boost 为 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820841/

相关文章:

c++ - 我可以重载模板变量吗?

c++ - Visual C++ 核函数 : boost include files not found

sql-server - 如何在 SQL Server 2005 中存储时区

java - 如何在java中查找本地/任何时区的时间戳过去的毫秒数

javascript - 使用 Angular 获取时区(只是时区)

c++ - 在 VTK 中设置相机和视锥体参数

c++ - 对类型的非常量左值引用 - 使用 Class 类型的参数时 Objective-C++ 包装器中的错误

c++ - C++ Intel Parallel Studio 2015 中的二维动态分配全局数组

c++ - 无法将简单的读/写串行端口代码从 boost::asio::serial_port 迁移到 QSerialPort

c++ - 类成员互斥断言失败