如何在 C# 中获取总小时数,它可能超过 24 小时

How to get Total hours in c#, it could be more than 24hours

我一个月需要个工作时间

ex : 7:30 + 8:00 + 6:30 +9:30 its 31:30 我需要回答 31:30 我试过 TimeSpan

 // create new timespan
  TimeSpan total = TimeSpan.Zero;

 // iterate through items
  foreach (var count in model.Items)
   {
      TimeSpan totalDonationSum = TimeSpan.Parse(count.Hours);
      total += totalDonationSum;
   }

我得到的总数是 1.06:21:00(如果超过 24 小时),我不想这样

让我帮忙,如果我做错了什么或者我会做一些不同的事情

使用TimeSpan.TotalHours属性。

您可以使用 TimeSpans 执行算术运算以获得 TimeSpan 作为结果,然后像这样

得到它的 TotaHours 属性
double totalHours = (TimeSpan.FromDays(1) + TimeSpan.FromHours(7)).TotalHours;
在这种情况下,

totalHours 的值为 31。

这样你就可以将小时和分钟分开:

// create new timespan
TimeSpan total = TimeSpan.Zero;

// iterate through items
foreach (var count in model.Items)
{
    TimeSpan totalDonationSum = TimeSpan.Parse(count.Hours);
    total += totalDonationSum;
}

// calculate
int hours = (int)total.TotalHours;
int minutes = total.Minutes;

// display
string time = hours.ToString("00") + ":" + minutes.ToString("00");

尝试用分钟来计算,最后格式为小时。

此代码应该可以帮助您:

int totalMinutes = 0;
foreach (var count in model.Items)
{
    DateTime totalDonationSum = DateTime.Parse(count.Hours);
    totalMinutes += (totalDonationSum.Hour*60) + totalDonationSum.Minute;
}

TimeSpan span = TimeSpan.FromMinutes(totalMinutes);
string hoursFormatThatYouWant = span.ToString(@"hh\:mm\:ss");

//If you use a console or you can change for MessageBox or Alert :)
Console.WriteLine("Total Hours:" + hoursFormatThatYouWant);

通过使用 TimeSpan.Hours 属性:

// Create a TimeSpan value with a large number of ticks. 
Console.Write("\n{0,-45}", "TimeSpan( 111222333444555 )"); 
ShowTimeSpanProperties(new TimeSpan(111222333444555));

Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Hours", interval.Hours, "TotalHours", interval.TotalHours);

来源:https://docs.microsoft.com/en-us/dotnet/api/system.timespan.hours?view=net-5.0