Feuermurmel
Feuermurmel

Reputation: 9922

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

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

When running this program at 2011-08-18 12:00:00 UTC, I expect the output 2011-08-18 14.00.00 UTC+02:00. Instead it prints 2011-08-18 12:00:00 UTC+00:00. i.e. Relative to the printed time zone, the printed time is correct, but it's not in the time zone I used to create the boost::local_time::local_date_time instance.

I currently use the technique suggested 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's content to the console
    cout << strm.str() << endl;

    return 0;
}

How should I convert the local_date_time instance to a string so the date in the string is represented using the time zone specified by the time_zone_ptr instance?

Upvotes: 4

Views: 6927

Answers (1)

Speckinius Flecksis
Speckinius Flecksis

Reputation: 624

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

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

in your code by

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

and everything works fine. If you want to use the common standard names, you have to create a timezone database as described in the boost documentation.

Upvotes: 3

Related Questions