C++ Utilities 5.32.1
Useful C++ classes and routines such as argument parser, IO and conversion utilities
Loading...
Searching...
No Matches
period.cpp
Go to the documentation of this file.
1#include "./period.h"
2
3namespace CppUtilities {
4
26
34{
35 m_years = end.year() - begin.year();
36 m_months = end.month() - begin.month();
37 if (m_months < 0) {
38 m_months += 12;
39 --m_years;
40 }
41 m_days = end.day() - begin.day();
42 if (m_days < 0) {
43 m_days += end.month() > 1 ? DateTime::daysInMonth(end.year(), end.month() - 1) : 31;
44 --m_months;
45 }
46 if (m_months < 0) {
47 m_months += 12;
48 --m_years;
49 }
50}
51
60{
61 auto year = begin.year() + period.years();
62 auto month = begin.month() + period.months();
63 if (month > 12) {
64 month -= 12;
65 ++year;
66 }
67 auto day = begin.day() + period.days();
68 const auto maxDays = DateTime::daysInMonth(year, month);
69 if (day > maxDays) {
70 day -= maxDays;
71 ++month;
72 }
73 if (month > 12) {
74 month -= 12;
75 ++year;
76 }
77 return DateTime::fromDate(year, month, day) + begin.timeOfDay();
78}
79
80} // namespace CppUtilities
Represents an instant in time, typically expressed as a date and time of day.
Definition datetime.h:55
int day() const
Returns the day component of the date represented by this instance.
Definition datetime.h:332
int month() const
Returns the month component of the date represented by this instance.
Definition datetime.h:324
static DateTime fromDate(int year=1, int month=1, int day=1)
Constructs a DateTime to the specified year, month, and day.
Definition datetime.h:209
constexpr TimeSpan timeOfDay() const
Returns the time of day as TimeSpan for this instance.
Definition datetime.h:416
static int daysInMonth(int year, int month)
Returns the number of days in the specified month and year.
Definition datetime.h:448
int year() const
Returns the year component of the date represented by this instance.
Definition datetime.h:316
Represents a period of time.
Definition period.h:8
constexpr int days() const
Returns the days component of the period represented by the current instance.
Definition period.h:48
constexpr int years() const
Returns the years component of the period represented by the current instance.
Definition period.h:32
constexpr int months() const
Returns the months component of the period represented by the current instance.
Definition period.h:40
constexpr Period()
Definition period.h:22
Contains all utilities provided by the c++utilities library.
CPP_UTILITIES_EXPORT DateTime operator+(DateTime begin, Period period)
Adds the specified period to the specified date.
Definition period.cpp:59