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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Program { static void Main(string[] args) { DateTime firstDateTime = DateTime.Now; DateTime secondDateTime = DateTime.Now.AddDays(3); TimeSpan dateTimeDifference; dateTimeDifference = secondDateTime.Subtract(firstDateTime); double totalHours = dateTimeDifference.TotalHours; Console.WriteLine("FirstDateTime: " + firstDateTime); Console.WriteLine("SecondDateTime: " + secondDateTime); Console.WriteLine("Total Hours Difference Between Two DateTime Object: " + totalHours); Console.ReadLine(); } } |
Output: