Search code examples
c++c++11c++-chrono

Add time duration to C++ timepoint


I have a starting timepoint in milliseconds like so:

using namespace std::chrono;
typedef time_point<system_clock, milliseconds> MyTimePoint;

MyTimePoint startTimePoint = time_point_cast<MyTimePoint::duration>(system_clock::time_point(steady_clock::now()));

Now I will have a certain number of hours that I want to add or subtract to the startTimePoint.

int numHours = -5//or 5 etc (Can be a plus or minus number)

How can I add this abount of time to the original startTimePoint??


Solution

  • If you want to add five hours to startTimePoint, it's boringly simple:

    startTimePoint += hours(5); // from the alias std::chrono::hours
    

    Live example.

    By the way, you're trying to convert a steady_clock::now() into a system_clock::time_point, which shouldn't even compile. Change the steady_clock::now() to system_clock::now() and you should be good to go.