[c#] Calculating how many minutes there are between two times

I have a datagridview in my application which holds start and finish times. I want to calculate the number of minutes between these two times. So far I have got:

var varFinish = tsTable.Rows[intCellRow]["Finish Time"];
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
int intMinutes = TimeSpan.FromMinutes(varTime);

But the last line won't compile because it says I am using invalid arguments for the Timespan constructor. I've researched quite a bit about how to calculate the number of minutes between two times, but I'm hitting a bit of a brick wall. Can someone please advise me on the best way to achieve my objective.

EDIT/

Now my code is as follows:

var varFinish = tsTable.Rows[intCellRow]["Finish Time"];
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
int intMinutes = (int)varTime.TotalMinutes;

But I am getting an invalid cast on the second line. Both varFinish and varValue are times e.g. 10:00 and 8:00 say. So not sure why they won't cast to type DateTime?

This question is related to c#

The answer is


In your quesion code you are using TimeSpan.FromMinutes incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:

public static TimeSpan FromMinutes(double value)

hence, the following code won't compile

var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile

Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:

TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue; 
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;

If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes; will always return (minutesDifference % 60). Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes(in different typecasts):

// Default value that is returned is of type *double* 
double double_minutes = endTime.Subtract(startTime).TotalMinutes; 
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes; 
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes; 
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes; 

double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);

TimeSpan.TotalMinutes: The total number of minutes represented by this instance.


You just need to query the TotalMinutes property like this varTime.TotalMinutes