-->

How to get a local date-time from a time_t with bo

2019-04-16 12:55发布

问题:

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?

回答1:

For this task, I'd ignore boost::date_time and just use localtime (or localtime_r, if available) from the standard library.



回答2:

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;
}


回答3:

Try this:

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

using namespace boost::posix_time;
using namespace std;

int main(int argc, char **argv) {

  cout << second_clock::local_time() << endl;

}

which on my box (Central time) yields:

$ ./boost_local_time
2011-May-26 14:00:18

If you want to format it (which was my test case), use

time_facet *facet = new time_facet("%d-%b-%Y %H:%M:%S");  
cout.imbue(locale(cout.getloc(), facet));   

before calling second_clock::local_time().