C++ Utilities  4.17.0
Useful C++ classes and routines such as argument parser, IO and conversion utilities
period.cpp
Go to the documentation of this file.
1 #include "./period.h"
2 
3 namespace ChronoUtilities {
4 
36 Period::Period(const DateTime &begin, const DateTime &end)
37 {
38  m_years = end.year() - begin.year();
39  m_months = end.month() - begin.month();
40  if (m_months < 0) {
41  m_months += 12;
42  --m_years;
43  }
44  m_days = end.day() - begin.day();
45  if (m_days < 0) {
46  m_days += end.month() > 1 ? DateTime::daysInMonth(end.year(), end.month() - 1) : 31;
47  --m_months;
48  }
49  if (m_months < 0) {
50  m_months += 12;
51  --m_years;
52  }
53 }
54 
63 {
64  auto year = begin.year() + period.years();
65  auto month = begin.month() + period.months();
66  if (month > 12) {
67  month -= 12;
68  ++year;
69  }
70  auto day = begin.day() + period.days();
71  const auto maxDays = DateTime::daysInMonth(year, month);
72  if (day > maxDays) {
73  day -= maxDays;
74  ++month;
75  }
76  if (month > 12) {
77  month -= 12;
78  ++year;
79  }
80  return DateTime::fromDate(year, month, day) + begin.timeOfDay();
81 }
82 
83 } // namespace ChronoUtilities
DateTime CPP_UTILITIES_EXPORT operator+(DateTime begin, Period period)
Adds the specified period to the specified date.
Definition: period.cpp:62
Period(const DateTime &begin, const DateTime &end)
Constructs a new Period defined by a start DateTime and an end DateTime.
Definition: period.cpp:36
int year() const
Returns the year component of the date represented by this instance.
Definition: datetime.h:235
static int daysInMonth(int year, int month)
Returns the number of days in the specified month and year.
Definition: datetime.h:367
Represents an instant in time, typically expressed as a date and time of day.
Definition: datetime.h:52
Contains classes providing a means for handling date and time information.
Definition: datetime.h:12
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:152
constexpr TimeSpan timeOfDay() const
Returns the time of day as TimeSpan for this instance.
Definition: datetime.h:335
int day() const
Returns the day component of the date represented by this instance.
Definition: datetime.h:251
Represents a period of time.
Definition: period.h:8
int days() const
Returns the days component of the period represented by the current instance.
Definition: period.h:40
int month() const
Returns the month component of the date represented by this instance.
Definition: datetime.h:243
int years() const
Returns the years component of the period represented by the current instance.
Definition: period.h:24
int months() const
Returns the months component of the period represented by the current instance.
Definition: period.h:32