A new answer for a decade-old question because times have changed and tools have gotten better.
In C++20, a date can be represented in several different succinct and useful ways.
std::chrono::sys_days
std::chrono::year_month_day
std::chrono::year_month_weekday
(this is not an exhaustive list)
Each data structure above represents a date, but has advantages and disadvantages, much like we have several container types that represent a sequence of values (vector
, list
, deque
, etc.) with advantages and disadvantages.
For adding days to a date, sys_days
is the clear best choice for a date representation. sys_days
is nothing but a count of days since (or before) 1970-01-01. It is a type alias for:
time_point<system_clock, days>
where days
is a std::chrono::duration
:
duration<
signed integer type of at least 25 bits, ratio_multiply<ratio<24>, hours::period>>
So adding days
to sys_days
is simply integral arithmetic under the hood.
And C++20 allows seamless conversion between {year, month, day}
concepts and sys_days
. So this looks like:
sys_days tp = sys_days{January/30/2022} + days{400}; // tp = 2023-03-06
Integrals can be used as inputs to the above formula. However when working with <chrono>
it is best to try and stay within the strong type system of <chrono>
.:
int y = 2022;
int m = 1;
int d = 30;
int num_days = 400;
sys_days tp = sys_days{month(m)/d/y} + days{num_days}; // tp = 2023-03-06
In any event, tp
can be easily observed by just printing it out:
cout << tp << '\n';
Output:
2023-03-06
Other formatting options are available, and programmatic access to the values for the year, month and day are also available. It is best to keep these values within the chrono strong types year
, month
and day
, but conversions to integral types are also available.