提升last_write_time回来一小时

时间:2018-02-27 14:12:37

标签: 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

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

1 个答案:

答案 0 :(得分:1)

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

E.g。如果你这样做

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