【问题标题】:C++ Chrono determine whether day is a weekend?C ++ Chrono确定一天是否是周末?
【发布时间】:2018-10-12 09:56:43
【问题描述】:

我有一个格式为年 (int)、月 (int) 和日 (int) 的日期,例如 2018、10、12 表示 2018 年 10 月 12 日。

有没有办法可以使用带有这些整数的 C++ Chrono 库来确定我的“日期”是否是周末?

如果没有,实现这一目标的最简单替代方法是什么?

【问题讨论】:

标签: c++ chrono


【解决方案1】:

在 C++20 中,您将能够做到这一点:

#include <chrono>

constexpr
bool
is_weekend(std::chrono::sys_days t)
{
    using namespace std::chrono;
    const weekday wd{t};
    return wd == Saturday || wd == Sunday;
}

int
main()
{
    using namespace std::chrono;
    static_assert(!is_weekend(year{2018}/10/12), "");
    static_assert( is_weekend(year{2018}/10/13), "");
}

如果输入自然不是constexpr,那么计算也不可能是。

据我所知,目前还没有人发布此功能,但是您可以使用 Howard Hinnant's datetime lib 开始使用此语法。您只需要将#include "date/date.h" 和一些using namespace std::chrono; 更改为using namespace date;

#include "date/date.h"

constexpr
bool
is_weekend(date::sys_days t)
{
    using namespace date;
    const weekday wd{t};
    return wd == Saturday || wd == Sunday;
}

int
main()
{
    using namespace date;
    static_assert(!is_weekend(year{2018}/10/12), "");
    static_assert( is_weekend(year{2018}/10/13), "");
}

这将适用于 C++17、C++14,如果您删除 constexpr,则适用于 C++11。它不会移植到 C++11 之前的版本,因为它确实依赖于 &lt;chrono&gt;

对于奖励积分,上述功能也适用于当前时间(UTC):

    assert(!is_weekend(floor<days>(std::chrono::system_clock::now())));

【讨论】:

  • 你能澄清一下这其中的哪一部分是 C++20 特有的吗?只是/ 运算符? weekday 部分?
  • 几乎所有内容都是特定于 C++20 的:sys_daysweekdaySaturdaySundayyearoperator/()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 2011-03-30
  • 2023-03-16
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多