How can I Populate a chrono::year With the Current Year?

↘锁芯ラ 提交于 2019-12-22 08:49:22

问题


So I understand from this question that the integer used in the construction of a chrono::year corresponds to the Anno Domini origin of 0.

So my question is, what if I wanted to get the current chrono::year. Is there a function for that? I can obviously do:

const auto time = std::time(nullptr);
const auto current_date = *std::gmtime(&time);
const chrono::year foo{ current_date.tm_year + 1900 };

But that seems like a pretty convoluted process. Is there anything better available to me?


回答1:


using namespace std::chrono;
year_month_day ymd = floor<days>(system_clock::now());
const year foo = ymd.year();



回答2:


Here's another way:

auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
struct tm *parts = std::localtime(&now_c);
std::cout << 1900 + parts->tm_year  << std::endl;


来源:https://stackoverflow.com/questions/52394623/how-can-i-populate-a-chronoyear-with-the-current-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!