如何使用std :: chrono库设置特定时间? [英] How do I set a specific time using the std::chrono library?

查看:141
本文介绍了如何使用std :: chrono库设置特定时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代替使用 std :: chrono :: system_clock :: now();

我想设置自己的小时/分钟/秒.类似于使用 struct tm 手动构造日期时间的方式.

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.

做到这一点的最佳方法是什么?

What is the best way of doing this?

推荐答案

< chrono> 提供的任何时钟均指一个纪元,它与您的输入增量所指的时间点不同.到(基于问题下方的评论).因此,您不应该尝试使用 std :: chrono :: time_point 实例(实例化时钟处理),而是使用 std:chrono :: duration .后者与您输入的任何参考时间点无关.根据此输入的单位,选择预定义的 std :: duration 实例化之一,例如

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). So you shouldn't try to use std::chrono::time_point instances (the instantiations clocks deal with), but instead a 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, e.g.

#include <chrono>

const int timestamp = getSecondsSinceMidnight();

const std::chrono::seconds sec{timestamp};

现在您可以继续进行操作,例如减去另一个时间戳等.

Now you can proceed with that, e.g. subtract another timestamp etc.

这篇关于如何使用std :: chrono库设置特定时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆