我的数据库中有10条记录,包括开始时间和结束时间。我能够用SUBTRACT函数计算持续时间值。现在我正在运行循环,我想根据持续时间值(或开始和结束值)计算工作小时数。
我尝试了AddHours和Add函数,但它给出了错误。不确定我是否正确使用它。
Datetime TotalHours = TotalHours.add(Duration)
Datetime TotalHours = TotalHours.addHours(Duration)
这就是我所做的。给出了转换错误。
我尝试编写一个函数,通过添加60分钟到小时和儿子来手动计算时间,但必须有一个更简单的方法。
答案 0 :(得分:1)
您可以使用TimeSpan
的实例来累积所有持续时间。
例如:
var durations = // Your collection of TimeSpan items goes here.
var totalDuration = new TimeSpan();
foreach (var duration in durations)
totalDuration += duration;
double totalHours = totalDuration.TotalHours; // Note: Includes fractional hours.
答案 1 :(得分:1)
假设Duration
是TimeSpan
:
var durations = ....
var total = new TimeSpan();
foreach (var duration in durations) // assuming durations is a collection of all the durations you have calculated
total = total.Add(duration);
Console.WriteLine(total.Hours); // "whole" hours, try TotalHours for fractional
Console.WriteLine((int)total.TotalHours); // whole amount of total hours, ie 1 day + 3 h = 27 h
答案 2 :(得分:0)
答案 3 :(得分:0)
使用TimeSpan类,例如:
public class FromTo
{
public DateTime From {get; set;}
public DateTime To {get; set;}
//other properties of your class
}
现在获取包含开始日期和结束日期的对象列表。之后,您可以在循环中添加结果:
public TimeSpan CalculateWorkTime(List<FromTo> fromto)
{
TimeSpan sum = new TimeSpan();
fromto.ForEach(p =>
{
sum += (p.To - p.From);
});
return sum;
}
告诉我它是否有效。问候;)