c++ - 如何使用 boost::date_time 从 time_t 获取本地日期时间?

标签 c++ datetime boost boost-date-time

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

我正在寻找一种从那个 time_t 获取本地时间的方法。我正在阅读文档,如果不提供时区,我找不到任何方法来执行此操作,我不知道,因为它取决于机器的区域设置,而且我找不到任何方法从中获取一个.

我错过了什么?

最佳答案

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

关于c++ - 如何使用 boost::date_time 从 time_t 获取本地日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6143569/

相关文章:

c++ - 基于条件模板的代码执行 C++

c++ - 为什么我的 for 循环在我的 void 函数中不起作用

python - 按时间间隔合并数据帧的有效方法

windows - Boost.test 和对 Boost.thread 的依赖?

c++ - 为什么没有 strand::wrap() 等同于 strand::post()?

Delphi tclientdataset .cds datetime 二进制时间格式解包

c++ - 在 WebSocket++ 中关闭连接后出错

c++ - 为什么 CMake 无法识别库,尽管它已由 'include_directories' 添加?

c++ - 为什么我不能运行具有特定文件名的 exe?

database - PostgreSQL SELECT LIKE 日期时间