I'm using boost::date_time and I got a time_t, that have been generated by a library using the time() function from the C standard library.
I'm looking for a way get a local time from that time_t. I'm reading the documentation and can't find any way to do this without providing a time zone, that I don't know about because it's dependant on the machine's locale, and I can't find any way to get one from it.
What am I missing?
For this task, I'd ignore boost::date_time
and just use localtime
(or localtime_r
, if available) from the standard library.
boost::posix_time::from_time_t()
#include <ctime>
#include <ostream>
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
boost::posix_time::ptime local_ptime_from_utc_time_t(std::time_t const t)
{
using boost::date_time::c_local_adjustor;
using boost::posix_time::from_time_t;
using boost::posix_time::ptime;
return c_local_adjustor<ptime>::utc_to_local(from_time_t(t));
}
int main()
{
using boost::posix_time::to_simple_string;
using boost::posix_time::from_time_t;
std::time_t t;
std::time(&t); // initalize t as appropriate
std::cout
<< "utc: "
<< to_simple_string(from_time_t(t))
<< "\nlocal: "
<< to_simple_string(local_ptime_from_utc_time_t(t))
<< std::endl;
}
来源:https://stackoverflow.com/questions/6143569/how-to-get-a-local-date-time-from-a-time-t-with-boostdate-time