为什么日历周数在星期一 3 a.m 更新,而不是在午夜?

Why calendar week number updates on Monday at 3 a.m., but not at midnight?

我正在使用 howardhinnant.github.io/iso_week.html 中的 iso_week.h 来计算给定日期的周数。但是,它看起来是在星期一 3 a.m 更新周数,而不是午夜。

例如这样的代码:

#include <iostream>
#include "iso_week.h"

int main() {
    using namespace iso_week;
    using namespace std::chrono;
    /* Assume we have two time points:
     * tp1 corresponds: Monday July 15 02:50:00 2019
     * tp2 corresponds: Monday July 15 03:00:00 2019
     */
    // Floor time points to convert to the sys_days:
    auto tp1_sys = floor<days>(tp1);
    auto tp2_sys = floor<days>(tp2);
    // Convert from sys_days to iso_week::year_weeknum_weekday format
    auto yww1 = year_weeknum_weekday{tp1_sys};
    auto yww2 = year_weeknum_weekday{tp2_sys};
    // Print corresponding week number of the year
    std::cout << "Week of yww1 is: " << yww1.weeknum() << std::endl;
    std::cout << "Week of yww2 is: " << yww2.weeknum() << std::endl;
}

输出为:

Week of yww1 is: W28
Week of yww2 is: W29

为什么要这样做?

这可能与您所在的时区有关吗?我知道很多企业都位于东海岸,"iso_week.h" 可能是基于那个时间,这意味着它可能是 运行 午夜,它只是告诉你它是 运行凌晨 3 点钟。如果不是这种情况,那么只 运行 晚上 9 点的节目是不是错了?

起初我没有注意到你的评论:

// Floor time points to convert to the sys_days:

这意味着tp1tp2是基于system_clock。和 system_clock 模型 UTC。

您可以使用tz.h header(tz.cpp来源)获取您当前的时区,将UTC时间点转换为本地时间点,然后将它们提供给year_weeknum_weekday。这会将一天的开始定义为您当地的午夜而不是 UTC 午夜。

这看起来像:

#include "date/iso_week.h"
#include "date/tz.h"
#include <iostream>

int
main()
{
    using namespace iso_week;
    using namespace date;
    using namespace std::chrono;
    auto tp1 = floor<seconds>(system_clock::now());
    zoned_seconds zt{current_zone(), tp1};
    auto tp1_local = floor<days>(zt.get_local_time());
    auto yww1 = year_weeknum_weekday{tp1_local};
    std::cout << "Week of yww1 is: " << yww1.weeknum() << std::endl;
}

current_zone() 查询您计算机的当前本地时区设置。如果您更喜欢其他时区,您可以将 current_zone() 替换为时区名称:

zoned_seconds zt{"Europe/Athens", tp1};

如果您想以比秒更精确的精度工作,zoned_seconds 只是 zoned_time<seconds> 的类型别名。所以使用你需要的任何精度(例如 zoned_time<milliseconds>)。

使用 tz.h 确实需要 some installation。不只是header。