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

时间:2018-07-27 15:57:11

标签: c# .net timespan

嗨,我必须执行一个小时的总和,要执行此操作,请使用下面的代码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

1 个答案:

答案 0 :(得分:4)

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

使用hhmm时,它将使用Hours对象的MinutesTimeSpan值,而不是TotalHours和{{ 1}}就是您想要的。

因此,如果您的总计小时数超过一天,则需要一天的前24小时。例如,如果您的总数是27个小时,那么您的TotalMinutes将是TimeSpan.Days,而1将是TimeSpan.Hours

这是与您完全相同的程序,但编写为简单的控制台程序。

3

输出为

  

03:30

但是,请在调试器中查看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(); } 的值。

enter image description here

因此,您的方法很好,您需要更好地打印它。 像这样:

tot

编辑:

使用下面的Matthew Watson的建议,将以您想要的确切格式提供输出。

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