How to get a local date-time from a time_t with boost::date_time?

偶尔善良 提交于 2019-12-06 13:47:50

问题


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


来源:https://stackoverflow.com/questions/6143569/how-to-get-a-local-date-time-from-a-time-t-with-boostdate-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!