将持续时间添加到C++时间点

Har*_*Boy 9 c++ c++11 c++-chrono

我有一个以毫秒为单位的起始时间点,如下所示:

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()));
Run Code Online (Sandbox Code Playgroud)

现在我将有一定的小时数我要添加或减去startTimePoint.

int numHours = -5//or 5 etc (Can be a plus or minus number)
Run Code Online (Sandbox Code Playgroud)

如何将这段时间添加到原始startTimePoint?

huu*_*huu 17

如果你想增加五个小时startTimePoint,它非常简单:

startTimePoint += hours(5); // from the alias std::chrono::hours
Run Code Online (Sandbox Code Playgroud)

实例.

顺便说一下,你正在尝试将a转换steady_clock::now()为a system_clock::time_point,甚至不应该编译.更改steady_clock::now()system_clock::now(),你应该很高兴去.

  • 我想补充一点,如果您的 time_point 具有比您要添加的单位更粗糙的时间分辨率,则它不适用于隐式转换,并且必须进行显式转换。fe 如果你想将纳秒(1)添加到steady_clock::now(),其分辨率为10ns,那么上面的代码不能直接工作。这是我今天缺少的一条信息...... (2认同)

小智 5

在这里,我以分钟为单位使用了时间,您可以从用户那里获得任何您想要的东西。所以下面是使用chrono的简单程序

#include <iostream>
#include <chrono>
using namespace std;
int main() {
    using clock = std::chrono::system_clock;
    clock::time_point nowp = clock::now();
    cout<<"Enter the time that you want to add in minutes"<<endl;
    int time_min;
    cin>>time_min;
    cin.ignore();
    clock::time_point end = nowp + std::chrono::minutes(time_min);
    time_t nowt =  clock::to_time_t ( nowp );
    time_t endt =  clock::to_time_t ( end);
    std::cout  << " " << ctime(&nowt) << "\n";
    std::cout << ctime(&endt) << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)