Michael WS Michael WS - 1 year ago 107
C++ Question

Boost log file names in a different timezone

I currently have a log process in boost
that is initialized with

keywords::file_name = (my_file_str + %Y-%m-%d_%H.%5N.log).c_str();

Is there any way to change the timezone of the datetime object? I would like to use a timezone that rolls at 5PM US/New_York namely EST-2EDT.

Answer Source

Yes, it is possible, here is a function generating a timestamp in US/NY:

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

std::string getNYCTimestamp() {
    boost::posix_time::ptime pt =
    boost::local_time::time_zone_ptr utc_zone(
        new boost::local_time::posix_time_zone("UTC"));
    boost::local_time::local_date_time utc_time(pt, utc_zone);

    boost::local_time::time_zone_ptr nyc_zone(
        new boost::local_time::posix_time_zone("EST-05:00:00EDT+01:00:00,M4.1.0/02:00:00,M10.5.0/02:00:00"));
    boost::local_time::local_date_time nyc_time = utc_time.local_time_in(nyc_zone);

    auto our_facet = new boost::gregorian::date_facet("%Y-%m-%d");
    auto os = std::ostringstream();
    os.imbue(std::locale(std::locale::classic(), our_facet));

    boost::posix_time::time_duration t = nyc_time.time_of_day();
    os << nyc_time.date() << "_"
       << std::setw(2) << std::setfill('0') << t.hours() << '-'
       << std::setw(2) << std::setfill('0') << t.minutes() << '-'
       << std::setw(2) << std::setfill('0') << t.seconds() << '.'
       << std::setw(6) << std::setfill('0') << t.fractional_seconds();
    return os.str();

Note, that "%Y-%m-%d_%H.%5N" is most probably wrong, because:

  1. it omits minutes and seconds
  2. it tries to fit nanoseconds (9 digits) into 5 symbols.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download