Boost - Formatting sub second precision time with a time stamp

放肆的年华 提交于 2019-12-07 23:58:31

Have a look at the boost::local_time::local_date_time class. You can specify a time zone and use the local microsecond clock to initialize it like

boost::local_time::local_date_time  my_ldt(boost::local_time::local_microsec_clock::local_time(new boost::local_time::posix_time_zone("EST-5EDT,M4.1.0,M10.5.0")));

You should then be able to use the facets to format to a string.

Edit: Full example:

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

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

int main(void)
{
    boost::posix_time::ptime  now = boost::posix_time::second_clock::local_time();
    boost::posix_time::ptime  utc = boost::posix_time::second_clock::universal_time();

    boost::posix_time::time_duration tz_offset = (now - utc);

    std::stringstream   ss;
    boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
    ss.imbue(std::locale(std::locale::classic(), output_facet));

    output_facet->format("%H:%M:%S");
    ss.str("");
    ss << tz_offset;

    boost::local_time::time_zone_ptr    zone(new boost::local_time::posix_time_zone(ss.str().c_str()));
    boost::local_time::local_date_time  ldt = boost::local_time::local_microsec_clock::local_time(zone);
    boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
    ss.imbue(std::locale(std::locale::classic(), output_facet));
    output_facet->format("%Y-%m-%d %H:%M:%S%f%Q");
    ss.str("");
    ss << ldt;
    std::cout << ss.str() << std::endl; // "2004-02-29 12:34:56.000789-05:00"

    std::cout << "Press return to exit" << std::endl;
    std::string wait_for_line;
    std::getline(std::cin, wait_for_line);

    return (0);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!