DateTime.Add() Method in C#


The DateTime.Add() method in C# is used to return a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

Syntax

Following is the syntax −

public DateTime Add (TimeSpan val);

Above, Val is the positive or negative time interval.

Example

Let us now see an example to implement the DateTime.Add() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 3, 7, 8, 0, 15);
      TimeSpan span = new TimeSpan(115, 0, 0, 0);
      DateTime d2 = d1.Add(span);
      System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1);
      System.Console.WriteLine("
New DateTime = {0:y} {0:dd}", d2);    } }

Output

This will produce the following output −

Initial DateTime = March 2019 07
New DateTime = June 2019 30

Example

Let us now see another example to implement the DateTime.Add() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 9, 7, 8, 0, 15);
      // subtracting days
      TimeSpan span = new TimeSpan(-75, 0, 0, 0);
      DateTime d2 = d1.Add(span);
      System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1);
      System.Console.WriteLine("
New DateTime = {0:y} {0:dd}", d2);    } }

Output

This will produce the following output −

Initial DateTime = September 2019 07
New DateTime = June 2019 24

Updated on: 06-Nov-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements