5

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?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288

2 Answers2

8
using namespace std::chrono;
year_month_day ymd = floor<days>(system_clock::now());
const year foo = ymd.year();
T.C.
  • 133,968
  • 17
  • 288
  • 421
  • Wow, that's clever. I love the idea of being free from all the pointer passing involved in C's time library. – Jonathan Mee Sep 18 '18 at 21:17
  • 4
    Fwiw, I've upvoted this answer. But I also wanted to clarify that this is the current year **in UTC**. If you want the current year in a specific time zone, that is doable using `chrono::zoned_time` (and will occasionally give you a different answer). The code to do this is essentially a superset of the code presented in this answer. – Howard Hinnant Sep 18 '18 at 21:37
  • What is the cast that allows `year_month_day ymd = floor(system_clock::now())`? I'm not seeing the conversion between a `time_point` and `year_mont_day`. – Jonathan Mee Sep 19 '18 at 13:16
  • 1
    `year_month_day` has an implicit `constexpr noexcept` constructor taking the single argument `const sys_days&`. `sys_days` is just a type alias for `time_point`. `floor(...)` converts the `system_clock::time_point` to a `sys_days`. – Howard Hinnant Sep 19 '18 at 13:53
0

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;
Gonen I
  • 5,576
  • 1
  • 29
  • 60