Convert boost :: posix_time :: ptime to string using custom timezone

I have an instance of boost::posix_time::ptime and would like to convert ("format") it to a string using this instance of boost::local_time::time_zone_ptr . Below is a test program showing what I have. It converts a ptime to local_date_time , which, in my opinion, expresses the time zone in addition to the time information.

When starting this program at 2011-08-18 12:00:00 UTC, I expect the release on 2011-08-18 14.00.00 UTC+02:00 . Instead, it prints 2011-08-18 12:00:00 UTC+00:00 . those. with respect to the printed time zone, the printed time is correct, but it is not in the time zone that I used to create the boost::local_time::local_date_time .

I am currently using the proposed method in this question to use a custom format string.

 #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 content to the console cout << strm.str() << endl; return 0; } 

How to convert a local_date_time instance to a string so that the date in the string is displayed using the time zone specified by the time_zone_ptr instance?

+4
source share
1 answer

I think boost does not know the time zone specifier. Replace

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

in your code

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

and everything works fine. If you want to use common standard names, you need to create a time zone database as described in the acceleration documentation.

+3
source

All Articles