Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating how many minutes there are between two times

Tags:

c#

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?

like image 479
PJW Avatar asked Jan 26 '12 11:01

PJW


People also ask

How do you calculate minutes between two times?

To calculate the minutes between two times, multiply the time difference by 1440, which is the number of minutes in one day (24 hours * 60 minutes = 1440).

How do I calculate the number of hours between two times in Excel?

Hours between two times with the cell formatted as "h" by using the TEXT function (4). Hours and minutes between two times with the cell formatted as "h:mm" by using the TEXT function (4:55). Hours, minutes, and seconds between two times with the cell formatted as "h:mm:ss" by using the TEXT function (4:55:00).

How do you calculate minutes into time?

The time in minutes is equal to the hours multiplied by 60.


1 Answers

Try this

DateTime startTime = varValue DateTime endTime = varTime  TimeSpan span = endTime.Subtract ( startTime ); Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes ); 

Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.

like image 131
Kane Avatar answered Oct 10 '22 01:10

Kane