liveBook · Manning

Std::chrono::hours

As explained in Learn C++ by Example

std::chrono::hours is a C++ chrono duration type whose period is one hour.

std::chrono::hours is a C++ duration type representing intervals measured in hours. Construct it directly with hours{23}, or use the readable 23h literal. section 4.2.2 section 4.2.3

Use hours when choosing a duration representation or converting between time scales:

  • Convert hours to a coarser duration such as days with duration_cast when precision may be lost. section 4.2.2
  • Convert an exact hour count to a finer-grained duration such as milliseconds through an implicit conversion. section 4.2.2
  • Write hours{12} or 12h; the h suffix is a chrono user-defined literal. section 4.2.3

Twenty-three hours converted to days

using namespace std::chrono; auto nearly_a_day = 23h; days a_day = duration_cast<days>(nearly_a_day); The result is 0d because conversion from hours to days truncates toward zero; converting back produces 0h. section 4.2.2 section 4.2.3

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';
}

Browse the complete conversion example showing hours, days, duration_cast, output, and the lossy round trip. section 4.2.2

How Learn C++ by Example covers it

How deep it goes
Explains construction, implicit and explicit conversions, precision loss, and the user-defined literal operator.
Examples
Uses hours{23}, 23h, conversion to days, a lossy round trip, and a duration-conversion listing.
What you can do after
Apply it via std::chrono to construct hour durations, select readable syntax, and convert intervals while recognizing truncation.
How it connects
Connects hours with std::chrono::duration, duration_cast, minutes, milliseconds, days, and chrono literals.

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.