使用 Sum 将字符串转换为时间跨度

Conversion of string into timespan with Sum

你好,我必须执行小时总和,为此我使用下面的代码 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

问题出在您的 tot.ToString(@"hh\:mm"); 行。

当您使用 hhmm 时,它使用 TimeSpan 对象的 HoursMinutes 值,而不是 TotalHoursTotalMinutes这就是你想要的。

因此,如果您的总小时数超过一天,则前 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();
}

输出为

03:30

但是,在调试器中查看 tot 的值。

所以你的方法很好你需要更好地打印它。 像这样:

Console.WriteLine("Total Hours = {0}", tot.TotalHours);

编辑:

使用下面 Matthew Watson 的建议将以您想要的格式给出输出。

Console.WriteLine(tot.ToString(@"d\.hh\:mm"));