![](/img/trans.png)
[英]How to retrieve the clock type of std::filesystem::file_time_type in C++17
[英]Lost about std::filesystem's clock conversions, in C++17 lacking clock_cast
不久前,我設法做到了,從文件系統到系統時鍾到 go,這要歸功於 SO:
int64_t toUSsecSinceEpochUTC(std::filesystem::file_time_type ftime) {
// see https://stackoverflow.com/a/35282833/103724
using namespace std::chrono;
auto sys_now = system_clock::now();
auto fil_now = decltype(ftime)::clock::now(); // i.e. C++20's file_clock
auto sys_ftime = time_point_cast<system_clock::duration>(ftime - fil_now + sys_now);
auto sys_ftime_usec = time_point_cast<microseconds>(sys_ftime);
return sys_ftime_usec.time_since_epoch().count();
}
但現在我想做相反的事情,我正在掙扎......這是我微弱的嘗試:
std::filesystem::file_time_type fromUSsecSinceEpochUTC(int64_t usec_utc) {
std::filesystem::file_time_type ftime;
using namespace std::chrono;
auto sys_now = system_clock::now();
auto fil_now = decltype(ftime)::clock::now(); // i.e. C++20's file_clock
std::chrono::microseconds usec(usec_utc);
ftime = ????
return ftime;
}
MSVC2019 抱怨auto res = sys_now - usec + fil_now;
和
error C2676: binary '+': 'std::chrono::time_point<std::chrono::system_clock,std::chrono::duration<std::chrono::system_clock::rep,std::chrono::system_clock::period>>' does not define this operator or a conversion to a type acceptable to the predefined operator
即穩定時鍾和系統時鍾之間的https://stackoverflow.com/a/35282833/103724中的代碼似乎不適用於文件系統時鍾。 雖然可能只是我沒有跟隨。
任何<chrono>
專家可以提供幫助嗎?
要填寫fromUSsecSinceEpochUTC
,您將:
std::filesystem::file_time_type
fromUSsecSinceEpochUTC(int64_t usec_utc) {
std::filesystem::file_time_type ftime;
using namespace std::chrono;
auto sys_now = system_clock::now();
auto fil_now = decltype(ftime)::clock::now(); // i.e. C++20's file_clock
microseconds usec(usec_utc);
time_point<system_clock, microseconds> tp_sys{usec};
return tp_sys - sys_now + fil_now;
}
話雖如此, system_clock
和file_clock
的時代之間的關系將是一個常數。 我相信 Windows file_clock
紀元是 1601-01-01 00:00:00 UTC。 這與system_clock
時期(1970-01-01 00:00:00 UTC)之間的差異是 13,4774 天或3'234'576h
。
這些知識使您無需調用now()
。
std::filesystem::file_time_type
to_file_time(std::chrono::system_clock::time_point sys_tp)
{
using namespace std::literals;
return std::filesystem::file_time_type{sys_tp.time_since_epoch() + 3'234'576h};
}
std::chrono::system_clock::time_point
to_sys_time(std::filesystem::file_time_type f_tp)
{
using namespace std::literals;
return std::chrono::system_clock::time_point{f_tp.time_since_epoch() - 3'234'576h};
}
上面我利用了先驗知識,即file_clock::duration
::duration 與 Windows 上的system_clock::duration
類型相同。 根據需要或需要添加演員表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.