C++20chrono:如何将time_point与month_day进行比较?
是否有一个现代和优雅的方式来确定月和日在time_point可变匹配给定的month_day变量?
例如,我想知道今天是否是圣诞节。我有以下代码:
#include <chrono>
bool IsTodayChristmas()
{
using namespace std::chrono;
constexpr month_day Christmas = {December / 25};
auto Now = system_clock::now();
// return Now == Christmas; // How to?
}
现代而优雅:我的意思是如果可能的话,我宁愿不使用旧的 C 类型(类似于std::time_t和std::tm)和字符串比较(类似于std::put_time)。
任何帮助,将不胜感激。
回答
您可以转换system_clock::now()为std::chrono::year_month_day通过型std::chrono::sys_days。在实践中,这可能看起来像
#include <chrono>
bool IsTodayChristmas() {
using namespace std::chrono;
constexpr month_day Christmas = {December / 25};
auto Now = year_month_day{floor<days>(system_clock::now())};
// either
return Now == Christmas / Now.year();
// or
return Now.month() / Now.day() == Christmas;
}
正如 Howard Hinnant 指出的那样,这将决定 UTC 的圣诞节。您更有可能在本地时区的圣诞节之后:要这样做,我们必须首先转换Now到我们的本地时区:(std::chrono::current_zone据我所知,libstdc++ 或 libc++ 尚未提供注释。)
bool IsTodayChristmas() {
using namespace std::chrono;
constexpr month_day Christmas = {December / 25};
auto Now_local = current_zone()->to_local(system_clock::now());
auto Today = year_month_day{floor<days>(Now_local)};
return Today == Christmas / Today.year();
}
- I'm rooting for you! 🙂
- If you need to know if it is Christmas in some place other than your local time, or UTC, then change `auto Now_local = current_zone()->to_local(system_clock::now());` to `auto Now_local = locate_zone("Australia/Sydney")->to_local(system_clock::now());` and everything else can stay the same. In dealing with time, getting the question right is often harder than getting the answer right. 🙂
- Upvoted. 🙂 Nice job. Yes, working directly with the `time_zone` `current_zone()` is a good way to do this. But using `zoned_time` is also a good way. `zoned_time` is essentially a higher-level convenience API over working with `time_zone` directly. But in this case doesn't buy that much convenience (nor does it cost much). Either way, getting the current local time, and flooring it to days-precision is the correct way to get the current local date and compare it to Christmas.
THE END
二维码