Visual Studio 2022(C++20)中如何打印当前年月日并赋值给year_month_day
解决C++20中打印当前年月日的问题
错误根源
你代码里的核心问题是使用了初始化列表{},导致auto today被推导为std::initializer_list<std::chrono::time_point<...>>类型,而非预期的时间点对象。这直接引发了后续输出和类型转换的编译错误。
修正步骤与代码
1. 正确获取日期时间点
首先去掉初始化列表的大括号,让today直接存储floor<days>后的时间点:
auto today = floor<days>(system_clock::now());
2. 转换为year_month_day类型
要将时间点转为年/月/日结构,需要先把时间点转换为sys_days(system_clock对应的日期类型),再构造year_month_day:
year_month_day ymd = sys_days(today);
3. 格式化打印
C++20推荐用std::format来格式化输出,也可以直接输出year_month_day的成员:
完整代码示例:
#include <iostream> #include <format> #include <chrono> using namespace std; using namespace chrono; int main() { // 获取当前日期的时间点(精确到天) auto today = floor<days>(system_clock::now()); // 转换为年-月-日结构 year_month_day ymd = sys_days(today); // 方式1:用std::format格式化输出 cout << format("当前日期:{}年{}月{}日\n", ymd.year(), ymd.month(), ymd.day()); // 方式2:直接输出各成员 cout << "年:" << ymd.year() << endl; cout << "月:" << ymd.month() << endl; cout << "日:" << ymd.day() << endl; system("pause"); return 0; }
补充说明
sys_days是std::chrono中用于表示系统时钟日期的类型,它和system_clock::time_point可以互相转换,是连接时间点和日历类型(如year_month_day)的桥梁。- 如果需要更复杂的日期格式,
std::format支持标准格式说明符,比如format("{:%Y-%m-%d}", ymd)可以直接输出YYYY-MM-DD格式的日期。
内容的提问来源于stack exchange,提问作者NextOne
相关产品推荐
相关产品推荐

