[英]How do I set a specific time using the std::chrono library?
Instead of using std::chrono::system_clock::now();
而不是使用
std::chrono::system_clock::now();
I would like to set my own specific hours\minutes\seconds.我想设置自己的特定小时\分钟\秒。 Similar to how one would go about using
struct tm
to manually construct a date-time.类似于 go 关于使用
struct tm
手动构造日期时间的方式。
What is the best way of doing this?这样做的最佳方法是什么?
I've found a solution I was looking for.我找到了我正在寻找的解决方案。 See: A solution by Howard Hinnant
请参阅: Howard Hinnant 的解决方案
Basically you should use a 24hr duration基本上你应该使用 24 小时的持续时间
using days = std::chrono::duration<int, std::ratio<86400>>;
auto last_midnight = std::chrono::time_point_cast<days>(std::chrono::system_clock::now());
Then add the 24hr timestamp to it:)然后将 24 小时时间戳添加到它:)
You can use UDLs(User defined Literals) to create duration.您可以使用 UDL(用户定义的文字)来创建持续时间。 Duration can be converted to timpoint via
std::chrono::time_point
's constructor.持续时间可以通过
std::chrono::time_point
的构造函数转换为 timpoint。
#include <iostream>
#include <chrono>
int main()
{
using namespace std::literals::chrono_literals;
auto nanoseconds_i = 3ns;
auto nanoseconds_f = 3.1ns;
std::cout << nanoseconds_i.count() << std::endl;
std::cout << nanoseconds_f.count() << std::endl;
}
Any clock provided by <chrono>
refers to an epoch, which is different from the point in time one your input delta refers to (based on the comments below the question). <chrono>
提供的任何时钟都是指一个纪元,这与您的输入增量所指的时间点不同(基于问题下方的评论)。 So you shouldn't try to use std::chrono::time_point
instances (the instantiations clocks deal with), but instead a std:chrono::duration
.所以你不应该尝试使用
std::chrono::time_point
实例(实例化时钟处理),而是使用std:chrono::duration
。 The latter is agnostic of any reference point in time, as is your input.后者与任何参考时间点无关,您的输入也是如此。 Depending on the unit of this input, pick one of the predefined
std::duration
instantiations, eg根据此输入的单位,选择预定义的
std::duration
实例之一,例如
#include <chrono>
const int timestamp = getSecondsSinceMidnight();
const std::chrono::seconds sec{timestamp};
Now you can proceed with that, eg subtract another timestamp etc.现在您可以继续进行,例如减去另一个时间戳等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.