0

I have a List of DateTimes

var times = CurrentMeter.SessionTimes.ToList();

How do I find the difference between them and add the results to a new List?

I want the hours, minutes, seconds and milliseconds between each datetime.

user3664321
  • 55
  • 1
  • 6
  • 3
    What do you mean by differences between them? Do you want the differences between every combination of every pair in your list? Or the difference against some specific time (eg, DateTime.Now)? – drch May 28 '14 at 07:54
  • What's your problem? Finding the difference between datetimes or whatever operation your trying to do between items in a list. What have you tried? – Nathan Cooper May 28 '14 at 07:54
  • Do you want to compare by Days, Hours, Minutes, Seconds or even include Milliseconds? – Johannes Wanzek May 28 '14 at 07:55
  • Hours, seconds, milliseconds – user3664321 May 28 '14 at 07:57
  • For a list of 4 items do you want to generate list with 3 items (pairs:0-1, 1-2, 2-3) or the list with 6 items (pairs:0-1, 0-2, 0-3, 1-2, 1-3, 2-3)? – Ulugbek Umirov May 28 '14 at 08:03

3 Answers3

1

A difference between two DateTime objects is a TimeSpan.

This function will calculate the time delta between each consecutive pair of DateTimes.

It will iterate through each time in times, subtract the previous value from it, and add the difference to your result list.

IEnumerable<TimeSpan> CalculateDeltas(IEnumerable<DateTime> times) {
    var time_deltas = new List<TimeSpan>();

    DateTime prev = times.First();
    foreach (var t in times.Skip(1)) {
        time_deltas.Add(t - prev);
        prev = t;
    }

    return time_deltas;
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0

Here's an example to calculate the difference between each item in the list. The results are stored in a List<double> and represent the total of seconds between each datetime.

var times = new List<DateTime>
{
    new DateTime(2014, 5, 28, 9, 57, 12),
    new DateTime(2014, 5, 28, 9, 57, 43),
    new DateTime(2014, 5, 28, 9, 58, 03),
    new DateTime(2014, 5, 28, 9, 59, 46),
    new DateTime(2014, 5, 28, 10, 0, 22),
};

var differences = new List<double>();

for(int i = 0; i < times.Count - 1; i++)
{
    differences.Add((times[i+1] - times[i]).TotalSeconds);
}

Output:

31 20 103 36

Abbas
  • 14,186
  • 6
  • 41
  • 72
0

How about:

var time = new []{
    DateTime.Parse("14-4-2012 00:00:00"),
    DateTime.Parse("14-4-2012 01:12:34"),
    DateTime.Parse("14-4-2012 12:44:33"),
    DateTime.Parse("14-4-2012 23:12:42"),
};

var result = time.Zip(time.Skip(1), (a, b) => b - a)
                 .Select(d => new {d.Hours, d.Minutes, d.Seconds})
                 .ToList();

result is now:

enter image description here

(Note that this is a very simply approach and only works for differences < 24h. If you have greater differences, take into account d.Days etc.)

sloth
  • 99,095
  • 21
  • 171
  • 219