多个 TimeSpan 的总和

Sum of multiple TimeSpan

我必须在 DataTable 中对更多时间跨度求和才能使用下面的代码,但是总和是错误的,这是什么原因造成的:

DataTable(dt) 值:

    09:21
    08:28
    08:46
    04:23

Total hours: 30,97 //97 minutes is not correct

C#代码:

 TimeSpan totaleOreMarcaTempo = TimeSpan.Zero;
 int conta = 0;     
 foreach (DataRow dr in dt.Rows)
 {  
    String OreMarcaTempo = tm.ConteggioOreGiornaliere(dr["Data"].ToString()); //This string contains at each cycle 09:21 08:28 08:46 04:23
    TimeSpan oreMarcatempo = TimeSpan.Parse(OreMarcaTempo.ToString());
    totaleOreMarcaTempo = totaleOreMarcaTempo + oreMarcatempo;
    conta++;
 }
  labelTotaleOreMarcaTempoMod.Text = "" + (int)totaleOreMarcaTempo.TotalHours + ":" + totaleOreMarcaTempo.Minutes.ToString(); //30:58

您必须更改格式。 0.98 小时 = 58.2 分钟

labelTotaleOreMarcaTempoMod.Text =string.Format ("{0:00}:{1:00}:{2:00}", 
           (int)totaleOreMarcaTempo.TotalHours, 
                totaleOreMarcaTempo.Minutes, 
                totaleOreMarcaTempo.Seconds); 

30.97 是正确的小时数。 表示“30小时97分钟”。

30.97 小时30 小时 58 分钟。 58 / 60 大约是 0.97.

我认为您只需要正确格式化您的字符串。格式化它的一种方法是:

@"{(int)yourTimeSpan.TotalHours}:{yourTimeSpan.Minutes}"

要打印出时间跨度 "correctly",只需使用正确的格式:

labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("c");

labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("hh':'mm");

编辑 请注意(感谢 Basin)第二种形式忽略了天数。

参考:Standard TimeSpan Format Strings and Custom TimeSpan Format Strings

30.97 正确(30.97 小时,其中 0.97 是小时(60 分钟 * 0.97 = 58 分钟),
您只需要将 TotalHours 的分数转换为分钟。

var raw = "09:21 08:28 08:46 04:23";
var totalTimespan = 
    raw.Split(" ")
       .Select(TimeSpan.Parse)
       .Aggregate(TimeSpan.Zero, (total, span) => total += span);

// Use integer value of TotalHours
var hours = (int)totalTimespan.TotalHours;
// Use actual minutes
var minutes = totalTimespan.Minutes


var output = $"{hours}:{minutes}";

var expected = "30:58";
output.Should().Be(expected); // Pass Ok

30.97 是正确的值,但不是 HH:mm 格式。

对我来说正确的解决方案是:

 var total = Math.Floor( totaleOreMarcaTempo.TotalMinutes / 60).ToString() + ":" + Math.Floor( totaleOreMarcaTempo.TotalMinutes % 60).ToString();