gpt4 book ai didi

c++ - 为什么日历周数在星期一凌晨 3 点更新,而不是在午夜?

转载 作者:太空狗 更新时间:2023-10-29 20:33:06 26 4
gpt4 key购买 nike

我正在使用来自 howardhinnant.github.io/iso_week.htmliso_week.h计算给定日期的周数。但是,它似乎在星期一凌晨 3 点而不是午夜更新周数。

例如这样的代码:

#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

为什么要这样做?

最佳答案

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

// 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 .它不仅仅是标题。

关于c++ - 为什么日历周数在星期一凌晨 3 点更新,而不是在午夜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57317841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com