Search code examples
c++durationc++-chrono

Getting duration value as double


Let's say, I have following duration value:

auto duration=12h+15min+99s+99ms;

I want to know how many hours that is (as double value).

When I do auto hours=std::chrono::duration_cast<std::chrono::hours>(duration), I get hours.count() which is int. What is the right way to get the value for the whole duration expressed as double?


Solution

  • using namespace std::chrono;
    
    // Create a double-based hours duration unit
    using dhours = duration<double, hours::period>;
    
    // Assign your integral-based duration to it
    dhours h = 12h+15min+99s+99ms;
    
    // Get the value
    cout << h.count();
    

    Or alternatively, simply divide your integral based duration by one double-based hours:

    cout << (12h+15min+99s+99ms)/1.0h << '\n';