简体   繁体   中英

Output boost::chrono::system_clock::time_point as local time with respect to UTC

I'm trying to output a boost::chrono::system_clock::time_point to a file stream such that it will display the local time, but with the difference to UTC time, eg:

2015-05-08 11:49:07.890992700 -0400

Based on the documentation that should be possible by using the time_fmt manipulator with the local timezone:

std::ofstream file("MyFile.txt");
boost::chrono::system_clock::time_point timePoint = boost::chrono::system_clock::now();
file << boost::chrono::time_fmt(boost::chrono::timezone::local)
     << timePoint;

However, the result I get is:

2015-05-08 11:49:07.890992700 Eastern Daylight Time

So basically, I'd like the "Eastern Daylight Time" time zone string to be replaced by the "-0400" time zone difference to UTC. I'm guessing that the result may depend on the system local settings. Is there a way I can achieve this no matter the system settings?

AFAIK the +HHMM format is known as POSIX timezones.

FWIW I guess you mean system_clock::now() , and here's some test runs on my system:

$ TZ='Asia/Kathmandu' ./test
2015-05-10 04:46:40.655817854 +0545

$ TZ='America/Detroit' ./test
2015-05-09 18:59:57.022323975 -0400

So it appears to indeed depend on platform and potentially configuration (however I don't think it depends on locale settings for the options).

Also see it Live On Coliru

//#include <boost/chrono/chrono_io.hpp>
#include <boost/chrono/time_point.hpp>
#include <boost/chrono/io/time_point_io.hpp>
#include <boost/chrono/chrono.hpp>
#include <iostream>

int main() {
    boost::chrono::system_clock::time_point timePoint = boost::chrono::system_clock::now();
    std::cout
        << boost::chrono::time_fmt(boost::chrono::timezone::local)
        << timePoint
        << "\n";
}

[1] I figured this one out using tzselect :

The following information has been given:

    United States
    Eastern Time - Michigan - most locations

Therefore TZ='America/Detroit' will be used.
Local time is now:  za mei  9 18:59:38 EDT 2015.
Universal Time is now:  za mei  9 22:59:38 UTC 2015.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM