xtd 0.2.0
Loading...
Searching...
No Matches

◆ add_months()

date_time xtd::date_time::add_months ( int32  months) const

Returns a new xtd::date_time that adds the specified number of months to the value of this instance.

Parameters
monthsA number of months. The months parameter can be negative or positive.
Returns
An object whose value is the sum of the date and time represented by this instance and months
Exceptions
xtd::argument_out_of_range_exceptionThe resulting xtd::date_time is less than xtd::date_time::min_value or greater than xtd::date_time::max_value.
-or-
months is less than -120,000 or greater than 120,000.
Examples
The following example adds between zero and fifteen months to the last day of December, 2015. In this case, the xtd::date_time::add_months method returns the date of the last day of each month, and successfully handles leap years.
#include <xtd/console>
#include <xtd/date_time>
#include <xtd/startup>
using namespace xtd;
class program {
public:
static auto main() {
auto dat = date_time {2015, 12, 31};
for (auto ctr = 0; ctr <= 15; ctr++)
console::write_line(dat.add_months(ctr).to_string("d"));
}
};
startup_(program::main);
// This code produces the following output :
//
// 12/31/2015
// 01/31/2016
// 02/29/2016
// 03/31/2016
// 04/30/2016
// 05/31/2016
// 06/30/2016
// 07/31/2016
// 08/31/2016
// 09/30/2016
// 10/31/2016
// 11/30/2016
// 12/31/2016
// 01/31/2017
// 02/28/2017
// 03/31/2017
Represents an instant in time, typically expressed as a date and time of day.
Definition date_time.h:85
#define startup_(main_method)
Defines the entry point to be called when the application loads. Generally this is set either to the ...
Definition startup.h:175
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.h:10
Remarks
This method does not change the value of this xtd::date_time object. Instead, it returns a new xtd::date_time object whose value is the result of this operation.
The xtd::date_time::add_months method calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting xtd::date_time object. If the resulting day is not a valid day in the resulting month, the last valid day of the resulting month is used. For example, March 31st + 1 month = April 30th, and March 31st - 1 month = February 28 for a non-leap year and February 29 for a leap year.