Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way to get the current year in C++

Tags:

c++

stream

time

std

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?

like image 575
Jonas Daverio Avatar asked Feb 02 '26 16:02

Jonas Daverio


1 Answers

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
}
like image 125
yumetodo Avatar answered Feb 05 '26 06:02

yumetodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!