C# DateTime Subtraction(DateTime, TimeSpan)
Description
DateTime Subtraction(DateTime, TimeSpan)
subtracts
a specified time interval from a specified date and time and returns a new
date and time.
Syntax
DateTime.Subtraction(DateTime, TimeSpan)
has the following syntax.
public static DateTime operator -(
DateTime d,
TimeSpan t
)
Parameters
DateTime.Subtraction(DateTime, TimeSpan)
has the following parameters.
d
- The date and time value to subtract from.t
- The time interval to subtract.
Returns
DateTime.Subtraction(DateTime, TimeSpan)
method returns An object whose value is the value of d minus the value of t.
Example
The following example demonstrates the Subtract method and the subtraction operator.
using System;//from w ww . j a va2 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.