2011-02-24 71 views
2

我有进出时间的日志。我想在日志中有一列是一次登录期间的总时间,并且是该人员在整个日志中的总登录时间。C#DateTime TimeSpan持续时间?

我一直在使用的时间间隔对象获得的第一时间,但在结果集中,而我翻腾不断加起来的总时间一直困扰我:

// Set duration of this visit 
timeInRoom = -(ieLog.Ingresstime - ieLog.Egresstime); 

我已经试过有另一种时间跨度变量来保存最后一次迭代的值,并添加timeInRoom,以便我可以有一个运行的计数器,但这似乎不工作。

我在猜测我是以这种错误的方式去做的。有任何想法吗?时间是结果集中的DateTime值。

谢谢。

+0

你如何添加你的时间跨度对象? – msarchet 2011-02-24 16:34:54

+0

我添加了DateTime对象,但是当我这样做时,结果是TimeSpan对象。 – rd42 2011-02-24 16:38:51

+0

请勿添加两个日期时间,请参阅我的示例以了解如何保持直线。 – 2011-02-24 17:29:42

回答

4

像这样的东西应该工作:

var timeInRoom = new TimeSpan(); 
foreach(var log in logs) 
{ 
    timeInRoom += log.Egresstime - log.IngressTime; 
} 

或者如果你LINQ的粉丝:

logs.Aggregate(new TimeSpan(), 
       (ts, log) => ts + (log.Egresstime - log.IngressTime)); 
+0

为什么使用var timeInRoom而不是TimeSpan timeInRoom? – rd42 2011-02-24 18:12:00

+0

@ rd42:这只是一个风格问题。有人看着那条线可以立即看到那个timeInRoom是一个TimeSpan(因为它是如何被初始化的),所以开发人员没有太多混淆的机会。编译器对待它完全一样。所以我宁愿避免不必要的重复('TimeSpan ... = new TimeSpan()')。 – StriplingWarrior 2011-02-24 18:26:35

4

尝试在你的脑袋分开DateTime和时间跨度的概念。时间跨度代表一个固定的时间量,不论它何时发生或发生。这只是一个单位的数字。相对于现在,DateTime代表了一个固定的空间时间值,并具有确定的值。

例如:

DateTime now = DateTime.Now; 
DateTime tomorrow = now.AddDays(1); 
DateTime yesterday = now.AddDays(-1); 
DateTime nextWeek = now.Add(TimeSpan.FromDays(7)); 
DateTime dayAfterNext = now.Add(TimeSpan.FromDays(1) + TimeSpan.FromDays(1)); 

TimeSpan twoDays = TimeSpan.FromDays(1) + TimeSpan.FromDays(1); 
TimeSpan oneMinute = TimeSpan.FromMinutes(2) - TimeSpan.FromMinutes(1); 
DateTime oneMinuteFromNow = now.Add(oneMinute); 

@StriplingWarrior的回答正确演示了如何保持运行总时间的流逝。

+0

感谢您的解释! – rd42 2011-02-24 18:11:30