C++ Logo

std-discussion

Advanced search

Re: std::chrono::system_clock vs std::chrono::utc_clock (C++20)

From: Jens Maurer <jens.maurer_at_[hidden]>
Date: Thu, 30 Jan 2025 11:24:04 +0100
On 30/01/2025 04.40, Enji Cooper (yaneurabeya) via Std-Discussion wrote:
> Hi all,
> I tried writing up a simple example for how to calculate the time in Unix epoch using std::time_t, and was a bit confused when I found out that there doesn’t seem to be a clean way to convert from `std::chrono::utc_clock::now()` to a `std::time_t` quantity, unlike `std::chrono::system_clock::to_time_t(..)`. Can someone help me understand if I need to convert to time_t using `std::chrono::system_clock`, and/or confirm that the standard library lacks a clear way to convert to/from `std::time_t` using `std::chrono::unix_clock`.

I'm not finding a mention of "unix_clock" in the standard. What are you talking about?

In any case, time_t is a value of the clock represented by std::chrono::system_clock.
If you're on a POSIX system, it will contain "POSIX time", which is almost, but not
quite, like UTC time, because it ignores the presence of leap seconds: midnight POSIX
time is always an integral multiple of 86400 POSIX-seconds away from midnight 1970-01-01.
In contrast, utc_clock expressly accounts for leap seconds, and uses SI seconds.

See [time.clock.utc.overview].

So, if you want a time_t value for a utc_clock time_point, you need to first
convert that time_point to system_clock and then call to_time_t on the latter.
There's clock_cast in [time.clock.cast.fn] to do that. Note: This is non-trivial,
because the number of UTC leap seconds that have elapsed at the
indicated time point need to be queried from some sort of database.

> I tried using g++ 13.13.0

That version number looks wrong.

Jens

Received on 2025-01-30 10:24:07