S
S
shasoft2020-09-09 17:06:26
C++ / C#
shasoft, 2020-09-09 17:06:26

How to convert FILETIME to time_t in C++?

In one place, the modified date is determined as
std::filesystem::last_write_time(filepath);
and with the help of the code

// Преобразовать дату/время файла в time_t
    template <typename TP> std::time_t to_time_t(TP tp)
    {
      using namespace std::chrono;
      auto sctp = time_point_cast<system_clock::duration>(tp - TP::clock::now()
        + system_clock::now());
      return system_clock::to_time_t(sctp);
    }

converted to time_t.

Elsewhere, the last modified date is defined as FILETIME and converted to time_t using the code
static std::time_t to_time_t(FILETIME ft)
    {
      std::time_t ret = 0;
      // Преобразовать в time_t
      ULARGE_INTEGER ull;
      ull.LowPart = ft.dwLowDateTime;
      ull.HighPart = ft.dwHighDateTime;
      ret = (ull.QuadPart / 10000000ULL - 11644473600ULL);
      return ret;
    }


But there is a problem, the time in time_t does not match . I have a difference of 1 second even though the file's modification date doesn't change. Is there some way to convert so that the values ​​are identical?

ps there is an idea to just minus 1 second in the second case, but I'm not sure that this will always be the right option. All the same, this formula is not just invented. This method with minus is not suitable, because I found an option when the time coincided :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shasoft, 2020-09-09
@shasoft

Here is the code. It gives the same result. At least for test cases

// Преобразовать в time_t
    static std::time_t to_time_t(const ULARGE_INTEGER& ull)
    {
      // Преобразовать в time_t
      std::time_t ret = (ull.QuadPart / 10000000ULL - 11644473600ULL);
      // Правильное оуркгление
      ULONGLONG QuadPartMod = ull.QuadPart % 10000000ULL;
      if (QuadPartMod >= 5000000ULL) {
        ret++;
      }
      //
      return ret;
    }
    static std::time_t to_time_t(const FILETIME& ft)
    {
      std::time_t ret = 0;
      // Преобразовать в ULARGE_INTEGER
      ULARGE_INTEGER ull;
      ull.LowPart = ft.dwLowDateTime;
      ull.HighPart = ft.dwHighDateTime;
      // Преобразовать в time_t
      return to_time_t(ull);
    }
    template <typename TP> std::time_t to_time_t(TP tp)
    {
      // Преобразовать в ULARGE_INTEGER
      ULARGE_INTEGER ull;
      ull.QuadPart = tp.time_since_epoch().count();
      // Преобразовать в time_t
      return to_time_t(ull);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question