更换Chrono :: Time_point的小时?
如何仅更改现有std :: Chrono :: System_clock :: Time_point
的时间?
例如,说我想实现此功能:
void set_hour(std::chrono::system_clock::time_point& tp, int hour) {
// Do something here to set the hour
}
std::chrono::system_clock::time_point midnight_jan_1_2022{std::chrono::seconds{1640995200}};
set_hour(midnight_jan_1_2022, 11);
// midnight_jan_1_2022 is now 11am on Jan 1 2022
....
How can I change just the hour of an existing std::chrono::system_clock::time_point
?
For example, say I wanted to implement this function:
void set_hour(std::chrono::system_clock::time_point& tp, int hour) {
// Do something here to set the hour
}
std::chrono::system_clock::time_point midnight_jan_1_2022{std::chrono::seconds{1640995200}};
set_hour(midnight_jan_1_2022, 11);
// midnight_jan_1_2022 is now 11am on Jan 1 2022
....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案完全取决于您的意思。最简单的解释是您要采取任何日期
tp
指向(例如yyyy-mm-dd HH:MM:S.FFF ...
),然后创建:yyyy-mm-dd小时:00:00.000 ...
。另一个可能的解释是
yyyy-mm-dd HH:mm:ss.fff ...
被转换为yyyy-mm-dd小时:mm:ss.fff ... 。
在任何一种情况下,C ++ 20都可以简单简单,如果您还没有访问C ++ 20
< chrono>
,则存在一个免费的开源标头库模拟C ++ 20< chrono>
并与C ++一起使用11/14/17。如果您想按第一个解释中所述的分钟,第二和子秒字段为零:
即,您只需将
time_point
将其置于days-precision中,然后添加所需的小时。第二个解释稍微复杂得多:
在这里,您必须发现并恢复{分钟,秒,子秒}字段才能将它们重新应用于所需的日期(以及所需的
hour
)。hh_mm_ss
是C ++ 20{小时,分钟,秒,subseconds}
数据结构,可以自动从持续时间转换为现场结构,以便更轻松地更换小时场。这两种解决方案都将为您的示例输入提供相同的答案:
由于输入的分钟数分钟,秒和子秒字段。
The answer depends on exactly what you mean. The simplest interpretation is that you want to take whatever date
tp
points to (sayyyyy-mm-dd hh:MM:ss.fff...
), and create:yyyy-mm-dd hour:00:00.000...
.Another possible interpretation is that
yyyy-mm-dd hh:MM:ss.fff...
is transformed intoyyyy-mm-dd hour:MM:ss.fff...
.In either event C++20 makes this easy, and if you don't yet have access to C++20
<chrono>
, then there exists a free, open-source header-only library that emulates C++20<chrono>
and works with C++11/14/17.If you want to zero the minute, second and subsecond fields as described in the first interpretation that is:
I.e. you simply floor the
time_point
to days-precision and then add the desired hours.The second interpretation is slightly more complicated:
Here you have to discover and recover the {minutes, seconds, subseconds} fields to re-apply them to the desired date (along with the desired
hour
).hh_mm_ss
is a C++20{hours, minutes, seconds, subseconds}
data structure that automates the conversion from a duration into a field structure so that you can more easily replace the hours field.Both of these solutions will give the same answer for your example input:
since the input has zeroed minutes, seconds and subseconds fields already.