boost last_write_time 回到一小时

标签 boost time boost-filesystem

我试图解决以下代码中的错误,其中我与 boost last_write_time 相差一个小时。

为了更好地解释它:我创建一个文件,然后尝试使用 boost::filesystem::path 提取它的创建时间。

void PrintTime(boost::filesystem::path _file) {
    time_t sys_time{ last_write_time(_file) };
    ptime p_time{ boost::posix_time::from_time_t(sys_time) };
    boost::posix_time::time_duration time_dur{ p_time.time_of_day() };

    long h{ time_dur.hours() }; //1a
    long m{ time_dur.minutes() };
    long s{ time_dur.seconds() };

    //...print h, m, s.
    }

    //1a: Here when for example the time I expect is 12:34:56,
    //I always get 11:34:56

知道这是为什么吗? boost的last_write_time中是否有时区? 当我通过系统检查文件时,我的操作系统显示正确的时间。

最佳答案

您必须转换为“演示”时区,例如“当[您]通过系统检查文件时”。文件系统的时间戳是 UTC 时间。

例如如果你这样做

std::cout << boost::posix_time::second_clock::local_time() << "\n";
std::cout << boost::posix_time::second_clock::universal_time() << "\n";

你可能会得到

2018-Feb-27 16:03:12
2018-Feb-27 15:03:12

修复:

#include <boost/date_time/c_local_time_adjustor.hpp>

void PrintTime(boost::filesystem::path _file) {
    using boost::posix_time::ptime;
    using adj = boost::date_time::c_local_adjustor<ptime>;

    time_t const sys_time = last_write_time(_file);
    ptime const utc       = boost::posix_time::from_time_t(sys_time);
    ptime const local     = adj::utc_to_local(utc);

演示

查看 Live On Coliru

#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/date_time/posix_time/conversion.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>

void PrintTime(boost::filesystem::path _file) {
    using boost::posix_time::ptime;
    using adj = boost::date_time::c_local_adjustor<ptime>;

    time_t const sys_time = last_write_time(_file);
    ptime const utc       = boost::posix_time::from_time_t(sys_time);
    ptime const local     = adj::utc_to_local(utc);

    std::cout << "utc: " << utc << "\n";
    std::cout << "local: " << local << "\n";
    {
        long h{ local.time_of_day().hours() };
        long m{ local.time_of_day().minutes() };
        long s{ local.time_of_day().seconds() };

        //...print h, m, s.
        std::cout << h << ":" << m << ":" << s << '\n';
    }
}

int main() {
    PrintTime("main.cpp");
}

打印(在我的系统上):

utc: 2018-Feb-27 15:19:45
local: 2018-Feb-27 16:19:45
16:19:45

关于boost last_write_time 回到一小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49010719/

相关文章:

c++ - Boost:支持在 O(log n) 时间内查找元素的优先级队列

c++ - 在 2 个线程中 boost 套接字

c++ - boost中的安全 bool 成语?

Java JFreeChart DynamicTimeSeriesCollection。如何让 x 轴显示当前时间?

c - 我的跳过列表真的是在 N 而不是 log(N) 中搜索吗?

windows - 为什么 boost::filesystem is_directory 在作为 Windows 服务运行时返回不同的结果?

c++ - 为什么 boost::filesystem::path 和 std::filesystem::path 的路径转义字符不同?

c++ - 使用 autoconf 找不到 boost 库 1.52

c++ - 无法将 Boost 路径迭代器转换为字符串

c - 如何将以微秒为单位的字符串转换为C中的struct tm?