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()
,你应该很高兴去.
小智 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)