DateTimeOffset.AddMonths() Method in C#


The DateTimeOffset.AddMonths() method in C# is used to add a specified number of months to the value of this instance.

Syntax

Following is the syntax −

public DateTimeOffset AddMonths (int val);

Above, Val is the number of months to be added. For subtracting months, set a negative value.

Example

Let us now see an example to implement the DateTimeOffset.AddMonths() method −

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 08, 10, 4, 20, 10, new TimeSpan(-5, 0, 0));
      Console.WriteLine("DateTimeOffset (before adding months) = {0}", dateTimeOffset);
      DateTimeOffset res = dateTimeOffset.AddMonths(3);
      Console.WriteLine("DateTimeOffset (after adding months) = {0}", res);
   }
}

Output

This will produce the following output −

DateTimeOffset (before adding months) = 8/10/2019 4:20:10 AM -05:00
DateTimeOffset (after adding months) = 11/10/2019 4:20:10 AM -05:00

Example

Let us now see another example to implement the DateTimeOffset.AddMonths() method −

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 08, 10, 4, 20, 10, new TimeSpan(-5, 0, 0));
      Console.WriteLine("DateTimeOffset (before subtracting months) = {0}", dateTimeOffset);
      DateTimeOffset res = dateTimeOffset.AddMonths(-5);
      Console.WriteLine("DateTimeOffset (after subtracting months) = {0}", res);
   }
}

Output

This will produce the following output −

DateTimeOffset (before subtracting months) = 8/10/2019 4:20:10 AM -05:00
DateTimeOffset (after subtracting months) = 3/10/2019 4:20:10 AM -05:00

Updated on: 11-Nov-2019

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements