DateTime.Subtract() Method in C#


The DateTime.Subtract() method in C# is used to subtract the specified DateTime or span.

Syntax

Following is the syntax −

public TimeSpan Subtract (DateTime value);
public DateTime Subtract (TimeSpan value);

Example

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

using System;
public class Demo {
   public static void Main() {
      DateTime d1 = new DateTime(2019, 10, 10, 8, 10, 40);
      DateTime d2 = new DateTime(2017, 11, 06, 8, 10, 40);
      Console.WriteLine("Date 1 = "+d1);
      Console.WriteLine("Date 2 = "+d2);
      TimeSpan res = d1.Subtract(d2);
      Console.WriteLine("TimeSpan between two dates = {0} ",res);
   }
}

Output

This will produce the following output −

Date 1 = 10/10/2019 8:10:40 AM
Date 2 = 11/6/2017 8:10:40 AM
TimeSpan between two dates = 703.00:00:00

Example

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

using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 10, 10, 8, 10, 40);
      TimeSpan t = new TimeSpan(1, 10, 10, 12);
      Console.WriteLine("Date = "+d);
      DateTime res = d.Subtract(t);
      Console.WriteLine("DateTime between date d and timespan t = {0} ",res);
   }
}

Output

This will produce the following output −

Date = 10/10/2019 8:10:40 AM
DateTime between date d and timespan t = 10/8/2019 10:00:28 PM
raja
Published on 07-Nov-2019 06:00:38
Advertisements