Thursday, January 1, 2015

Working with WinRT DateTime in C++

DateTime in managed languages has a very comprehensive set of methods that make working with it very easy, C++/CX not so much. Some answers on stackoverflow suggest using ATL and all kinds of other very complicated solutions. Here is my entry into this fight, if I can convert DateTime -> std::chrono::seconds and std::chrono::seconds -> DateTime then I can use the entirely reasonable set of functions that surrounds std::chrono.

DateTime toFileTime(std::chrono::seconds sec)
    long long unixTime = sec.count();
    DateTime result;
    result.UniversalTime = unixTime * 10000000ULL + 116444736000000000LL;
    return result;

std::chrono::seconds toDuration(DateTime dt)
    return std::chrono::seconds((dt.UniversalTime - 116444736000000000LL) / 10000000ULL);

Now this is assuming that seconds is a duration from Unix epoch, you can easily get the current distance from epoch using time(nullptr) or std::chrono::system_clock::now().time_since_epoch().count()

No comments:

Post a Comment