嗨,我必须执行总小时数,为此我使用下面的代码 c#:首先将 hourtot 转换为时间跨度然后我执行总和,最后总和我得到 08:30,这是不可能的,我怎么能解决这个?这是因为什么?
C# 代码:
/*
hourtot values:
08:30
10:00
09:00
08:30
10:00
10:30*/
TimeSpan tot= TimeSpan.Zero;
foreach (DataRow dr in dt.Rows)
{
String hourtot= r.CaricaOreGiornaliere(dr["date"].ToString());
if(hourtot.Equals("00:00") == false)
{
TimeSpan hourcant= TimeSpan.Parse(hourtot.ToString());
tot= tot+ hourcant;
}
}
labelris.text = "" + tot.ToString(@"hh\:mm"); //this print 08:30
Run Code Online (Sandbox Code Playgroud)
问题出在你的tot.ToString(@"hh\:mm");线路上。
当您使用hh和mm,它使用Hours与Minutes您的值TimeSpan对象,而不是TotalHours和TotalMinutes这是你想要的。
因此,如果您的总小时数超过一天,则前 24 小时将作为一天。例如,如果您的总时数为 27 小时,那么您TimeSpan.Days将是1,并且TimeSpan.Hours将是3。
这是与您完全相同的程序,但编写为一个简单的控制台程序。
static void Main(string[] args)
{
List<string> times = new List<string>();
times.Add("08:30");
times.Add("10:00");
times.Add("09:00");
TimeSpan tot = TimeSpan.Zero;
foreach (var time in times)
{
if (time.Equals("00:00") == false)
{
TimeSpan hourcant = TimeSpan.Parse(time);
tot = tot + hourcant;
}
}
Console.WriteLine(tot.ToString(@"hh\:mm"));
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
输出是
03:30
但是,查看tot调试器内部的值。
所以你的方法很好,你需要更好地打印它。像这样的东西:
Console.WriteLine("Total Hours = {0}", tot.TotalHours);
Run Code Online (Sandbox Code Playgroud)
使用下面的 Matthew Watson 建议将提供您想要的确切格式的输出。
Console.WriteLine(tot.ToString(@"d\.hh\:mm"));
Run Code Online (Sandbox Code Playgroud)