Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get TimeSpan in minutes given two Dates?

Tags:

c#

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?

like image 231
Sreedhar Avatar asked Jun 23 '09 06:06

Sreedhar


People also ask

How do I convert DateTime to TimeSpan?

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.

How do I get the difference between two dates and minutes in C#?

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.

How do I get the time between two dates in C#?

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.


2 Answers

TimeSpan span = end-start; double totalMinutes = span.TotalMinutes; 
like image 125
Josh Avatar answered Sep 21 '22 04:09

Josh


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.

like image 31
David Božjak Avatar answered Sep 19 '22 04:09

David Božjak