Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::filesystem::file_time_type from time_t – how?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do it in two steps:

  1. time_t to system_clock::time_point via std::chrono::system_clock::from_time_t
  2. system_clock::time_point to file_clock::time_point via std::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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading