diff --git a/Examples-and-Recipes.md b/Examples-and-Recipes.md index 18c6e62..92a4b23 100644 --- a/Examples-and-Recipes.md +++ b/Examples-and-Recipes.md @@ -25,6 +25,7 @@ This page contains examples and recipes contributed by community members. Feel f - [What is the epoch difference between Unix Time and GPS time?](#unix_gps_epoch_diff) - [How to convert to/from C++ Builder's TDate and TDateTime](#TDate) - [How to convert to/from QDate](#QDate) +- [How to convert to/from Windows' FILETIME](#FILETIME) *** @@ -1240,6 +1241,44 @@ Here are functions you can use to convert between [`QDate`](http://doc.qt.io/qt- These work by simply adjusting the epoch of these two types. + +### How to convert between Windows' `FILETIME` and `system_clock` +(by [Billy O'Neal](https://github.com/BillyONeal)) + +Here are functions and typedefs you can use to work with Windows' [FILETIME](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx) structure. + +Assuming `system_clock` is based on the Unix epoch: + + using std::ratio; + using std::chrono::duration; + using std::chrono::duration_cast; + using std::chrono::system_clock; + + // filetime_duration has the same layout as FILETIME; 100ns intervals + using filetime_duration = duration>; + // January 1, 1601 (NT epoch) - January 1, 1970 (Unix epoch): + constexpr duration nt_to_unix_epoch{INT64_C(-11644473600)}; + + system_clock::time_point FILETIME_to_system_clock(FILETIME fileTime) { + const filetime_duration asDuration{static_cast( + (static_cast(fileTime.dwHighDateTime) << 32) + | fileTime.dwLowDateTime)}; + const auto withUnixEpoch = asDuration + nt_to_unix_epoch; + return system_clock::time_point{ + duration_cast(withUnixEpoch)}; + } + + FILETIME system_clock_to_FILETIME(system_clock::time_point systemPoint) { + const auto asDuration = duration_cast( + systemPoint.time_since_epoch()); + const auto withNtEpoch = asDuration - nt_to_unix_epoch; + const uint64_t rawCount = withNtEpoch.count(); + FILETIME result; + result.dwLowDateTime = static_cast(rawCount); // discards upper bits + result.dwHighDateTime = static_cast(rawCount >> 32); + return result; + } + *** ![CC BY Logo](http://mirrors.creativecommons.org/presskit/buttons/80x15/svg/by.svg) _This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/)._ \ No newline at end of file