开发者

C# DateTime TimeSpan duration?

I have a log of in and out times. I want to have a column in the log be the total time during one login and next to that the total login times for that person for the entire log.

I've been getting the first duration using the TimeSpan object, but to continually add up the total time while I churn through the result set has eluded me:

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

I've tried having anoth开发者_开发知识库er TimeSpan variable to hold the value of the last iteration and add timeInRoom to that so I could have a running tally, but that doesn't appear to be working.

I'm guessing that I'm going about this the wrong way. Any ideas? The times are DateTime values in the result set.

Thanks.


Something like this should work:

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

Or if you're a fan of LINQ:

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


Try to separate DateTime and TimeSpan concepts in your head. TimeSpans represent a fixed amount time irrespective of when it occurs or occurred. It is just a number with a unit. DateTime represents a fixed time in space with a definite value with respect to now.

For example:

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's answer correctly demonstrates how to keep a running total of time elapsed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜