r/cpp_questions•
Vanariu

Representing dates & times in UTC

SOLVED

I'm looking for a portable (between windows, mac osx and linux) way to represent a date & time in C++. Specifically, I am dealing with parsing data which has UTC times which I need to ensure are stored as their correct UTC value and compare them with the system's clock in UTC.

I've looked at std::chrono, and the C time library (ctime). There does not appear to be any way I can see of constructing an arbitrary std::chrono::timepoint without using from_time_t(), the ctime structure based on the unix epoch. std::chrono apparently has an undefined epoch behavior - the standard does not state it has to be the unix epoch. I am not sure it is a good idea to proceed with std::chrono if this is the case.

The C api has portability issues when attempting to construct a UTC time from an arbitrary month, day, year, hour, min, second. A tm structure can be created, but can only be converted to time_t representation with mktime, which stores it as the local system time, not UTC. In linux (and mac osx?), there's a timegm extension function that does this. In windows, that function doesn't exist, but there's _mkgmtime, however this seems to be non-standard and might go away in the future.

I can proceed with the C api way but it seems ugly and might break, especially in windows. Is there some better way I'm not seeing? I'd like to avoid using something like boost due to the dependency issues it pulls in.

Posted Feb 21, 2016, 10:08 PM UTC

24
Loading comments…