问题
I'm struggling to figure out how to preform a conversion with boost::date_time.
I want to convert a millisecond value measured from the Unix epoch (00:00, Jan 1, 1970) to a human readable string - something like: 2/13/2012 15:20:11
would be ideal.
I've tried some std C++ / boost suggestions I've seen but not had any luck just yet. Here is the code I use:
long long ticksFromEpoch = 1329117220501;
std::time_t tt = static_cast<time_t>(ticksFromEpoch);
boost::posix_time::ptime dt = boost::posix_time::from_time_t(tt);
// 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("UTC"));
boost::local_time::local_date_time dt_with_zone(dt, zone);
std::stringstream strm;
strm.imbue(std::locale(std::cout.getloc(), new boost::local_time::local_time_facet("%Y-%m-%d %H:%M:%S"))); // 15:14
strm << dt_with_zone;
// Print the stream's content to the console
std::cout << strm.str() << std::endl;
The output is: 2032-07-01 20:20:37
which is clearly incorrect. I suspect that I'm not constructing the ticksFromEpoch
variable correctly but I'm not sure why. Can anyone point me in the right direction? Any help is much appreciated!!
回答1:
time_t
is usually seconds since "the epoch", rather than milliseconds.
If you dont care about milliseconds you should be able to do this:
std::time_t tt = static_cast<time_t>(ticksFromEpoch/1000)
If you do care about milliseconds you can either add them back in at the end (which is tricky to get right for times like 12:00:00.001 AM )
Or you'll need to go another route. You may need to use something like this: (untested)
boost::posix_time::ptime t2(
date(1970,Jan,1), //The epoch
boost::posix_time::seconds( ticksFromEpoch / 1000 ) + // Number of seconds
boost::posix_time::microseconds( ticksFromEpoch % 1000) // And the micros too.
);
来源:https://stackoverflow.com/questions/9257078/converting-millisecond-utc-to-human-readable-date-time