使用自定义时区将 boost::p osix_time::p time 转换为字符串

Convert boost::posix_time::ptime to string using custom time zone

本文关键字:time 自定义 转换 字符串 osix boost 时区      更新时间:2023-10-16

我有一个boost::posix_time::ptime实例,想使用给定的boost::local_time::time_zone_ptr实例将其转换("格式化"(为字符串。下面是一个测试程序,显示了我目前拥有的内容。它将ptime转换为local_date_time,根据我的理解,除了时间信息外,还表示时区。

在 2011-08-18 12:00:00 UTC 运行此程序时,我希望输出2011-08-18 14.00.00 UTC+02:00。相反,它打印2011-08-18 12:00:00 UTC+00:00.即相对于打印的时区,打印的时间是正确的,但它不在我用于创建boost::local_time::local_date_time实例的时区中。

我目前使用此问题中建议的技术来使用自定义格式字符串。

#include <iostream>
#include <ctime>
#include <boost/date_time.hpp>
int main(int argc, char ** argv) {
    using namespace std;
    // Get current time, as an example
    boost::posix_time::ptime dt = boost::posix_time::microsec_clock::universal_time();
    // Create a time_zone_ptr for the desired time zone and use it to create a local_date_time
    boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone("EST"));
    boost::local_time::local_date_time dt_with_zone(dt, zone);
    std::stringstream strm;
    // Set the formatting facet on the stringstream and print the local_date_time to it.
    // Ownership of the boost::local_time::local_time_facet object goes to the created std::locale object.
    strm.imbue(std::locale(std::cout.getloc(), new boost::local_time::local_time_facet("%Y-%m-%d %H:%M:%S UTC%Q")));
    strm << dt_with_zone;
    // Print the stream's content to the console
    cout << strm.str() << endl;
    return 0;
}

我应该如何将local_date_time实例转换为字符串,以便使用time_zone_ptr实例指定的时区表示字符串中的日期?

我认为 boost 不知道时区说明符。取代

new boost::local_time::posix_time_zone("EST")

在您的代码中由

new boost::local_time::posix_time_zone("EST-05:00:00")

一切正常。如果要使用通用标准名称,则必须按照提升文档中的说明创建时区数据库。