Search code examples
windows-runtimec++-winrt

How to get the current time in UTC?


I'm trying to get the current time in UTC in a UWP application. This should be a simple matter of constructing a DateTime object

DateTime const now{ clock::now() };

and accessing its UniversalTime field. However, that field does not appear to have been projected into C++/WinRT.

How do I get the current time in UTC using C++/WinRT?


Solution

  • Looks like a documentation bug. That field doesn't exist in C++/WinRT. Instead, DateTime is projected as a std::chrono::time_point. But similar to C++/CX, the documentation for the struct (not the field) is still somewhat accurat - it has the same granularity as FILETIME. But even easier than extracting the value youself, winrt::clock provides static methods to_file_time and to_time_t that convert DateTime to FILETIME or time_t, respectively.

    I'll get the documentation fixed up, and I've been meaning to write a blog post about how C++/WinRT seamlessly interops with std::chrono for timekeeping. I'm a fan of std::chrono, and incorporating it into C++/WinRT was my idea, so the haters know who to blame. :)