Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi I have to run uses sum of time differences in the following format:
StartEnd[0]: 08:50
StartEnd1: 10:30
StartEnd[2]: 12:30
StartEnd[3]: 15:30

result=(StartEnd 1 -StartEnd[0])+(StartEnd[3]-StartEnd[2])


How can I get the result value in the HH: mm format?


What I have tried:

C# Code:
<pre>TimeSpan totalSum = TimeSpan.Zero;
foreach (DataRow dr in dt.Rows)
{
    string[] HourAndMinute = dr["StartEnd"].ToString().Split(); 
    TimeSpan tsStart = TimeSpan.Parse(HourAndMinute[0].Trim());
    TimeSpan tsEnd = TimeSpan.Parse(HourAndMinute[1].Trim());
    totalSum += tsEnd - tsStart;
}
Posted
Updated 5-Jul-18 14:17pm

Convert each time to minutes:
08:50 ==> (08 * 60) + 50 ==> 530
10:30 ==> (10 * 60) + 50 ==> 650
Then
(StartEnd 1 -StartEnd[0]) ==> 650 - 530 ==> 120 minutes
and so on.
When you have the result in minutes, it simple to use divide to get the hours, and modulus to get the minutes:
C#
int hours = result / 60;
int minutes = result % 60;
 
Share this answer
 
TimeSpan ts0 = TimeSpan.Parse( "08:50" );
TimeSpan ts1 = TimeSpan.Parse( "10:30" );
TimeSpan ts2 = TimeSpan.Parse( "12:30" );
TimeSpan ts3 = TimeSpan.Parse( "15:30" );

int minutes = (int) ( ts1.TotalMinutes - ts0.TotalMinutes + ts3.TotalMinutes - ts2.TotalMinutes );
TimeSpan ts = new TimeSpan( 0, minutes, 0 );

Console.WriteLine( $"HH: {ts.Hours:D2} mm: {ts.Minutes:D2}" );
 
Share this answer
 
Quote:
Add the difference in hours and minutes in C#

Hours are decimal, minutes are decimal, but a time (hours + minutes) is not decimal.
But hours and minutes are linked: 1 hour is 60 minutes.
So to do 'time arithmetic', you need to handle this particularity.
You have mostly 2 possibility:
- use the standard datetime datatype, it will handle all details for you.
- create your own solution: converting the hours to minutes look the easiest.

Basically, your procedure is:
convert the times to minutes
do whatever arithmetic operation you need
covert result back to times
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900