< Back to Calendar

Calendar.AddMonths Method

public abstract int AddMonths(int year, int month, int day, int value);

Parameters

year

The year.

month

The month.

day

The day.

value

The number of months to add (can be negative to subtract months).

Returns

An integer representing the month after the specified number of months has been added. The month is represented by a number from 1 to 12.

Remarks

The AddMonths method adds a specified number of months to a date. The month component of the returned date is adjusted, and the year component is adjusted if necessary. The day component remains the same, unless the resulting month has fewer days than the original day, in which case the day is adjusted to the last day of the resulting month.

This method is abstract and must be implemented by derived calendar classes.

Example

C# Example

using System;
using System.Globalization;

public class Example
{
    public static void Main()
    {
        // Using the GregorianCalendar
        Calendar gregorianCalendar = CultureInfo.InvariantCulture.Calendar;

        int year = 2023;
        int month = 10; // October
        int day = 26;
        int monthsToAdd = 3;

        // Add 3 months to October 26, 2023
        int newMonth = gregorianCalendar.AddMonths(year, month, day, monthsToAdd);

        Console.WriteLine($"Original Date: {year}-{month}-{day}");
        Console.WriteLine($"Months to Add: {monthsToAdd}");
        Console.WriteLine($"Resulting Month: {newMonth}"); // Expected output: 1 (January)

        // Example with day adjustment
        year = 2024;
        month = 1; // January
        day = 31;
        monthsToAdd = 1;

        // Add 1 month to January 31, 2024
        newMonth = gregorianCalendar.AddMonths(year, month, day, monthsToAdd);
        Console.WriteLine($"Original Date: {year}-{month}-{day}");
        Console.WriteLine($"Months to Add: {monthsToAdd}");
        Console.WriteLine($"Resulting Month: {newMonth}"); // Expected output: 2 (February, day will be adjusted to 29 as 2024 is a leap year)

        // Example with negative monthsToAdd
        monthsToAdd = -15;
        newMonth = gregorianCalendar.AddMonths(year, month, day, monthsToAdd);
        Console.WriteLine($"Original Date: {year}-{month}-{day}");
        Console.WriteLine($"Months to Add: {monthsToAdd}");
        Console.WriteLine($"Resulting Month: {newMonth}"); // Expected output: 10 (October)
    }
}