[英]C++ 20 chrono: How to compare time_point with month_day?
Is there a modern and elegant way to determine if the month and day in a time_point
variable match a given month_day
variable?是否有一种现代而优雅的方法来确定
month_day
变量中的月份和日期是否与给定的time_point
变量匹配?
For example, I want to know if today is Christmas.例如,我想知道今天是不是圣诞节。 I have the following code:
我有以下代码:
#include <chrono>
bool IsTodayChristmas()
{
using namespace std::chrono;
constexpr month_day Christmas = {December / 25};
auto Now = system_clock::now();
// return Now == Christmas; // How to?
}
Modern and elegant: I mean if possible, I would prefer not to use old C types (something like std::time_t
and std::tm
) and string comparisons (something like std::put_time
).现代而优雅:我的意思是,如果可能的话,我宁愿不使用旧的 C 类型(类似于
std::time_t
和std::tm
)和字符串比较(类似于std::put_time
)。
Any help would be appreciated.任何帮助,将不胜感激。
You can convert system_clock::now()
to a std::chrono::year_month_day
type via a std::chrono::sys_days
.您可以通过
std::chrono::sys_days
chrono::sys_days 将system_clock::now()
转换为std::chrono::year_month_day
类型。 In practice this might look something like在实践中,这可能看起来像
#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;
}
As Howard Hinnant pointed out, this will determine Christmas in UTC.正如 Howard Hinnant 指出的那样,这将决定 UTC 的圣诞节。 You're more likely to be after Christmas in the local time zone: to do so, we must first transform
Now
into our local time zone: (Note std::chrono::current_zone
is not yet provided by libstdc++ or libc++, as far as I can tell.)您更有可能在本地时区的圣诞节之后:为此,我们必须首先将
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.