You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++ <chrono>库实现计算指定年份复活节日期的函数?

用C++ 库计算复活节日期

实现思路

复活节日期的计算可基于高斯复活节算法,结合C20引入的<chrono>库组件,能直接返回year_month_day或sys_days类型的日期结果,适配现代C的日期时间处理体系。

完整函数实现

以下是返回year_month_day类型的实现(若需要sys_days,只需转换返回值即可):

#include <chrono>

using namespace std::chrono;

// 返回给定年份的复活节日期,类型为year_month_day
year_month_day easter(year y)
{
    const int Y = static_cast<int>(y);
    // 高斯算法核心计算步骤
    const int a = Y % 19;
    const int b = Y / 100;
    const int c = Y % 100;
    const int d = b / 4;
    const int e = b % 4;
    const int f = (b + 8) / 25;
    const int g = (b - f + 1) / 3;
    const int h = (19 * a + b - d - g + 15) % 30;
    const int i = c / 4;
    const int k = c % 4;
    const int l = (32 + 2 * e + 2 * i - h - k) % 7;
    const int m = (a + 11 * h + 22 * l) / 451;
    // 计算月份和日期
    const int month_idx = (h + l - 7 * m + 114) / 31;
    const int day_idx = (h + l - 7 * m + 114) % 31 + 1;

    return {y, month{month_idx}, day{day_idx}};
}

// 若需要返回sys_days类型,可使用如下重载
sys_days easter_sys(year y)
{
    return sys_days{easter(y)};
}

适用年份范围说明

上述实现基于格里高利历的高斯算法,有效适用范围为1583年至4099年:

  • 1582年之前欧洲普遍使用儒略历,复活节计算需采用儒略历版本的算法,上述代码不兼容该场景;
  • 4099年之后,高斯算法的参数会出现精度偏差,无法准确计算复活节日期,需要对算法参数进行调整。

内容的提问来源于stack exchange,提问作者Howard Hinnant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:27:48