I need a function that can return the difference between the below two dates as 24.
DateTime a = new DateTime(2008, 01, 02, 06, 30, 00); DateTime b = new DateTime(2008, 01, 03, 06, 30, 00);
The difference between two dates can be calculated in C# by using the substraction operator - or the DateTime. Subtract() method. The following example demonstrates getting the time interval between two dates using the - operator.
The TimeSpan struct represents a duration of time, whereas DateTime represents a single point in time. Instances of TimeSpan can be expressed in seconds, minutes, hours, or days, and can be either negative or positive.
To get the difference between two-time, subtract time1 from time2. A result is a timedelta object. The timedelta represents a duration which is the difference between two-time to the microsecond resolution. To get a time difference in seconds, use the timedelta.
You can do the following:
TimeSpan duration = b - a;
There's plenty of built in methods in the timespan class to do what you need, i.e.
duration.TotalSeconds duration.TotalMinutes
More info can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With