To get TimeSpan in minutes from given two Dates I am doing the following
int totalMinutes = 0; TimeSpan outresult = end.Subtract(start); totalMinutes = totalMinutes + ((end.Subtract(start).Days) * 24 * 60) + ((end.Subtract(start).Hours) * 60) +(end.Subtract(start).Minutes); return totalMinutes;
Is there a better way?
To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property.
DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 8, 17, 11, 14, 25); Now, calculate the difference between two dates. TimeSpan ts = date2 - date1; To calculate minutes.
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.
TimeSpan span = end-start; double totalMinutes = span.TotalMinutes;
Why not just doing it this way?
DateTime dt1 = new DateTime(2009, 6, 1); DateTime dt2 = DateTime.Now; double totalminutes = (dt2 - dt1).TotalMinutes;
Hope this helps.
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