开发者

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

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开发者_StackOverflow社区 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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜