In short, the following get_this_year()
function should work for you in a C++20 way.
It will return you an int
for the current year.
// year.cpp
#include <chrono>
#include <iostream>
int get_current_year() {
using namespace std::chrono;
return static_cast<int>(
year_month_day{time_point_cast<days>(system_clock::now())}.year());
}
int main() {
int year = get_current_year();
std::cout << year << std::endl; // 2022
}
This should compile with e.g. g++ -std=c++20 year.cpp
.
But I also would like to expand it in a verbose way, explaining what happened for each step.
// year.cpp
#include <chrono>
#include <iostream>
int get_current_year() {
using namespace std::chrono;
auto now = system_clock::now(); // 1. get time_point for now
auto today = time_point_cast<days>(now); // 2. cast to time_point for today
auto ymd = year_month_day(today); // 3. convert to year_month_day
auto year = ymd.year(); // 4. get year from year_month_day
return static_cast<int>(year); // 5. an explicit cast is required
}
int main() {
int year = get_current_year();
std::cout << year << std::endl; // 2022
}
Now, even more verbosely, explicitly spelling out all the types -
// year.cpp
#include <chrono>
#include <iostream>
int get_current_year() {
std::chrono::time_point<std::chrono::system_clock,
std::chrono::system_clock::duration>
now = std::chrono::system_clock::now();
std::chrono::time_point<std::chrono::system_clock, std::chrono::days> today =
std::chrono::time_point_cast<std::chrono::days>(now);
std::chrono::year_month_day ymd = std::chrono::year_month_day(today);
std::chrono::year year = ymd.year();
return static_cast<int>(year);
}
int main() {
int year = get_current_year();
std::cout << year << std::endl; // 2022
}
There are essentially 2 types of format to represent a point in time:
- serial-based - e.g. this time point is
x
seconds since an epoch (e.g. 1 Jan 1970)
- field-based - e.g. this time point is
year/month/day
From the system clock we get a serial-based time point. We need to convert it to a field-based time point. Then from this field-based time point we extract the year.