I want to create a std::filesystem::file_time_type from a std::time_t and I can’t figure out how.
Example:
time_t t = 1337;
std::filesystem::file_time_type ft = ...; //how?
Ideally I would like this to work with c++17 but I’ll take a c++20 solution too.
>Solution :
You can do it in two steps:
time_ttosystem_clock::time_pointviastd::chrono::system_clock::from_time_tsystem_clock::time_pointtofile_clock::time_pointviastd::chrono::clock_cast
Altogether:
auto from_time_t_to_file_clock(std::time_t tt) {
auto st = std::chrono::system_clock::from_time_t(tt);
return std::chrono::clock_cast<std::chrono::file_clock>(st);
}
There is an optional function std::chrono::file_clock::from_sys that you can use instead for step 2, but it’s optional (there might be a from_utc instead), and the clock_cast will just do the right thing anyway, so might as well just use it.