What is the proper way to create Date object in C++? I want C++ analogy of this python code:
import datetime
x = datetime.date(2020, 5, 17)
delta = datetime.timedelta(days=1)
x = x + delta
I was reading about chrono and found only time_point https://en.cppreference.com/w/cpp/chrono/time_point
but I don't see constructor like this date(year=2020, month=1, day=2)
A date object is available in the standard library since c++20.
#include <chrono>
#include <iostream>
int main ()
{
std::chrono::year_month_day date(
std::chrono::year(2023),
std::chrono::month(5),
std::chrono::day(7));
std::cout << "Year: " << static_cast<int>(date.year())
<< ", Month: " << static_cast<unsigned>(date.month())
<< ", Day: " << static_cast<unsigned>(date.day()) << '\n';
}
Even though stream output should exist it is not available in the demo environment above, hence the manual cast of each value prior to output.
Arithmetic operations like the one you mention are provided either as:
date += months
)date1 + months
)Note that the year(), month(), day()
methods return object that are not the same as the corresponding specializations for duration (std::chrono::years
, std::chrono::months
, std::chrono::days
) but merely integral representation of the count of such quantities (hence the static cast to int
is ok). That said, you can perform arithmetic operations with the corresponding durations.