I'm quite new to C++. I need to get the current year and store it in an int.
I've come to this solution:
std::time_t result = std::time(nullptr);
std::istringstream iss(ctime(&result));
iss.ignore(20);
int year;
iss >> year;
I find this solution a bit ugly, even if it works, as it doesn't seem very robust and it takes many steps to do not very much.
Would there be a better way to do it?
C++20, you can use std::chrono for such purpose.
P0355R7 Extending to Calendars and Time Zones
#include <iostream>
#include <format>
#include <chrono>
int main()
{
const auto now = std::chrono::system_clock::now();
std::cout << std::format("{:%Y}", now); // => 2021
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With