从编译时已知的日历日期创建`std :: chrono :: time_point` [英] Creating a `std::chrono::time_point` from a calendar date known at compile time

查看:241
本文介绍了从编译时已知的日历日期创建`std :: chrono :: time_point`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

答案显示了如何将字符串解析为 std :: chrono :: time_point ,如下所示:

This answer shows how to parse a string to a std::chrono::time_point, as follows:

std::tm tm = {};
std::stringstream ss("Jan 9 2014 12:35:34");
ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));

如果我想创建 std :: chrono :: time_point 来自某个(格里高利历)日历日期,该日历日期的年,月,日在编译时是已知的,是否有比上述字符串解析更简单的方法?

If I want to create a std::chrono::time_point from a (Gregorian) calendar date whose year, month, and day-of-month are known at compile time, is there any simpler way than parsing it from a string as suggested above?

推荐答案

是的,您可以在编译时进行整个计算,创建一个 constexpr system_clock :: time_point 使用 Howard Hinnant的日期/时间库

Yes, you can do the entire computation at compile time, creating a constexpr system_clock::time_point using Howard Hinnant's date/time library.

#include "date/date.h"
#include <chrono>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    constexpr system_clock::time_point tp = sys_days{January/9/2014} + 12h + 35min + 34s;
    static_assert(tp == system_clock::time_point{1389270934s}, "");
}

这是假定日期/时间为UTC。如果不是,则必须手动添加/减去UTC偏移量。由于时区规则一直在政客的心血来潮中进行更改,因此使它们成为 constexpr 的希望很小。当误解暴露时,甚至历史时区规则也会更新。

This is assuming that the date/time is UTC. If it isn't, you will have to manually add/subtract the UTC offset to make it so. As time zone rules are changed at the whim of politicians all the time, there is little hope in making them constexpr. Even historical time zone rules are updated when misunderstandings come to light.

此外,该程序还将通过删除 #include date移植到C ++ 20 /date.h 使用命名空间日期; 。同样使用 Howard Hinnant的日期/时间库需要C ++ 14 constexpr 肌肉。 C ++ 11 constexpr 是不够的(但是您可以在运行时做到,将 constexpr static_assert )。

Also this program will port to C++20 by dropping #include "date/date.h" and using namespace date;. Also using Howard Hinnant's date/time library requires C++14 constexpr muscle. C++11 constexpr is not sufficient (but you can do it at run-time, dropping the constexpr and static_assert).

这篇关于从编译时已知的日历日期创建`std :: chrono :: time_point`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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