std::chrono::days is a C++20 chrono duration representing 24-hour day intervals. Use it to report elapsed time in days or connect durations with calendar dates. section 4.2.2 section 4.2.5
Key behavior:
- Convert a coarser duration to days explicitly with duration_cast<days>. section 4.2.2
- Expect truncation toward zero when conversion loses precision: 23 hours becomes 0 days. section 4.2.2
- Convert days back to hours implicitly when the destination is finer-grained. section 4.2.2
Countdown to New Year's Eve
Floor the current time_point to days, construct December 31 from the current year, subtract now from that event, and cast the result to days. section 4.2.5
Listing 4.4 Using duration to move to a coarser representation
void durations()
{
using namespace std::chrono;
auto nearly_a_day = hours{23}; #1
days a_day = duration_cast<days>(nearly_a_day); #2
hours round_trip = a_day; #3
std::cout << nearly_a_day << " cast to " << a_day
<< " and cast back to " << round_trip << '\n';
}
Shows a complete conversion from 23 hours to days and back, including the resulting precision loss. section 4.2.2
Listing 4.7 Finding how many days there are until the last day of the year
void countdown()
{
using namespace std::chrono;
time_point now = system_clock::now();
const auto ymd = year_month_day{
floor<days>(now) #1
};
auto this_year = ymd.year(); #2
auto new_years_eve = this_year / December / 31; #2
auto event = sys_days(new_years_eve);
duration dur = event - now;
std::cout << duration_cast<days>(dur) #3
<< " until event \n ";
}
int main()
{
countdown();
}
Shows days used with system_clock, year_month_day, sys_days, and duration_cast in a practical countdown. section 4.2.5
