C++20 adds these free functions to namespace std::chrono:
constexpr bool is_am(const hours& h) noexcept;
Returns:
0h <= h && h <= 11h.
constexpr bool is_pm(const hours& h) noexcept;
Returns:
12h <= h && h <= 23h.
But I don't have hours. I have a std::chrono::time_point. How can I find out if my time_point is am or pm?
In general, you can't. For example
steady_clock::time_pointhas no relationship whatsoever to human created times, dates or calendars. It is like a stopwatch. So it would be senseless to try to find out if asteady_clock::time_pointis am or pm.However it does make sense for those
time_points associated withsystem_clock(UTC, akastd::chrono::sys_time<Duration>), and those associated with a local time (std::chrono::local_time<Duration>).To see how to do this, it is instructive to form 4 overloads:
However, all of these are very similar. So I'll just show how to do the first. And to derive the first, it is instructive to first break it into tiny bits at a time. But in the end, it will wrap up into one line of code.
It is convenient to issue a function-local using directive to cut down on the verbosity of having
std::chrono::sprinkled all over the place. If you prefer the sprinkling, skip the using directive.First start the process of deconstructing the
time_pointinto fields such as {y, m, d, H, M, S}. Though only the hours field is really needed. The first step in this to extract the date as a days-precisiontime_point, labeledtpdabove.Next, find the time-of-day (
tod). It is just the "date_time - date".The hours can be extracted from the time-of-day using the
floorfunction again.Finally just return
is_amon the extracted hours.This can be more concisely wrapped up as just:
The exact same implementation can be used for the
local_timeoverload. And when you make theis_pmoverloads, just remember to switch outis_amforis_pmin the definitions.These can be called like this: