我有一个 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 实例的时区。

我目前使用建议的 in this question 技术来使用自定义格式字符串。

#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")

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

关于c++ - 使用自定义时区将 boost::posix_time::ptime 转换为字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7108059/

10-12 17:43
查看更多