如何使用boost::date_time从time_t中获取本地日期时间

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

本文关键字:time 获取 时间 日期 何使用 boost date      更新时间:2023-10-16

我正在使用boost::date_time,我得到了一个time_t,它是由一个库使用C标准库中的time()函数生成的。

我正在寻找一种从时间中获取当地时间的方法。我正在阅读文档,如果不提供时区,我找不到任何方法来做到这一点,我不知道时区,因为它取决于机器的区域设置,我也找不到从中获取时区的任何方法。

我错过了什么?

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

对于此任务,我将忽略boost::date_time,只使用标准库中的localtime(或localtime_r,如果可用)。