在C#中添加小时和分钟的差异 [英] Add the difference in hours and minutes in C#

查看:101
本文介绍了在C#中添加小时和分钟的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

推荐答案

每次转换为分钟:

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:

int hours = result / 60;
int minutes = result % 60;


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});
"HH: {ts.Hours:D2} mm: {ts.Minutes:D2}" );


这篇关于在C#中添加小时和分钟的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆