I have trying to solve a bug on the following code, where I get an hour difference from boost last_write_time.
To explain it better: I create a file, and then I try to extract the time it was created with 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
Any idea why is that? Is there timezone somewhere in boost last_write_time? My os displays the right time when I check the file through the system.
You have to translate to the "presentation" time-zone, like "when [you] check the file through the system". The timestamp from the filesystem is UTC time.
E.g. if you do
std::cout << boost::posix_time::second_clock::local_time() << "\n";
std::cout << boost::posix_time::second_clock::universal_time() << "\n";
you'll probably get
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);
See it 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");
}
Prints (on my system):
utc: 2018-Feb-27 15:19:45
local: 2018-Feb-27 16:19:45
16:19:45