Subtract date and time from date and time and returns a time interval in CSharp

Description

The following code shows how to subtract date and time from date and time and returns a time interval.

Example


using System;/*from   w  w w .  j av  a2 s .  c om*/
public class MainClass{
  public static void Main(String[] argv){  
            System.DateTime date1 = new System.DateTime(2014, 6, 3, 22, 15, 0);
      System.DateTime date2 = new System.DateTime(2014, 12, 6, 13, 2, 0);
      System.DateTime date3 = new System.DateTime(2014, 10, 12, 8, 42, 0);

      // diff1 gets 185 days, 14 hours, and 47 minutes.
      System.TimeSpan diff1 = date2.Subtract(date1);
            System.Console.WriteLine(diff1);

      // date4 gets 4/9/2014 5:55:00 PM.
      System.DateTime date4 = date3.Subtract(diff1);
            System.Console.WriteLine(date4);


      // diff2 gets 55 days 4 hours and 20 minutes.
      System.TimeSpan diff2 = date2 - date3;
            System.Console.WriteLine(diff2);

      // date5 gets 4/9/2014 5:55:00 PM.
      System.DateTime date5 = date1 - diff2;
            System.Console.WriteLine(date5);
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var