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
