How to subtract two DateTimes in C# – Programming Code Examples
C# C# Console Application

How to subtract two DateTimes in C#1 min read

The following c# example code demonstrate us how can we subtract two DateTime objects programmatically at run time in an console application. .Net framework’s DateTime.Subtract() method allow us to subtract the specified time or duration from this instance. DateTime.Subtract() method is overloaded, those are DateTime.Subtract(DateTime) and DateTime.Subtract(TimeSpan).

DateTime.Subtract(DateTime) overloaded method subtract the specified date and time from the instance. We need to pass a DateTime object to this method as parameter. This method return a System.TimeSpan type value. The return TimeSpan object represent a time interval that is equal to date and time of instance minus date and time of parameter.




DateTime.Subtract(TimeSpan) overloaded method subtract the specified duration from this instance. This method required to pass a TimeSpan object as parameter. The TimeSpan represent the time interval to subtract. This overloaded method return a System.DateTime object which is equal to date and time of instance minus time interval of parameter.

After getting the return TimeSpan value from DateTime.Subtract(DateTime) method, we can convert the TimeSpan to total days, hours, minutes, seconds etc. So we can get total days, hours, minutes difference between two date time objects.

C# Code:

Output:

How to subtract two DateTimes in C#

How to subtract two DateTimes in C#

Leave a Comment