Added FILETIME conversions

Billy O'Neal
2016-09-22 10:23:56 -07:00
parent 5f03382cee
commit 574bf0c8ef

@@ -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.
<a name="FILETIME"></a>
### 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<int64_t, ratio<1, 10'000'000>>;
// January 1, 1601 (NT epoch) - January 1, 1970 (Unix epoch):
constexpr duration<int64_t> nt_to_unix_epoch{INT64_C(-11644473600)};
system_clock::time_point FILETIME_to_system_clock(FILETIME fileTime) {
const filetime_duration asDuration{static_cast<int64_t>(
(static_cast<uint64_t>(fileTime.dwHighDateTime) << 32)
| fileTime.dwLowDateTime)};
const auto withUnixEpoch = asDuration + nt_to_unix_epoch;
return system_clock::time_point{
duration_cast<system_clock::duration>(withUnixEpoch)};
}
FILETIME system_clock_to_FILETIME(system_clock::time_point systemPoint) {
const auto asDuration = duration_cast<filetime_duration>(
systemPoint.time_since_epoch());
const auto withNtEpoch = asDuration - nt_to_unix_epoch;
const uint64_t rawCount = withNtEpoch.count();
FILETIME result;
result.dwLowDateTime = static_cast<DWORD>(rawCount); // discards upper bits
result.dwHighDateTime = static_cast<DWORD>(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/)._