Murat Oğuzhan
Murat Oğuzhan

Reputation: 885

Calculate total minutes in list of datetime

I have list of Appointment class. In below code;

And total time is 4+3+1=8,

How can i find 8 in given Appointment datetime values.

    class Program
    {
        static void Main(string[] args)
        {
            List<Appointment> appointments = new List<Appointment>();

            Appointment appointment1 = new Appointment();
            appointment1.StartDate = new DateTime(2018, 07, 11, 08, 00, 00);
            appointment1.FinishDate = new DateTime(2018, 07, 11, 11, 00, 00);

            Appointment appointment2 = new Appointment();
            appointment2.StartDate = new DateTime(2018, 07, 11, 10, 00, 00);
            appointment2.FinishDate = new DateTime(2018, 07, 11, 12, 00, 00);

            Appointment appointment3 = new Appointment();
            appointment3.StartDate = new DateTime(2018, 07, 11, 09, 00, 00);
            appointment3.FinishDate = new DateTime(2018, 07, 11, 12, 00, 00);

            Appointment appointment4 = new Appointment();
            appointment4.StartDate = new DateTime(2018, 07, 11, 14, 00, 00);
            appointment4.FinishDate = new DateTime(2018, 07, 11, 16, 00, 00);

            Appointment appointment5 = new Appointment();
            appointment5.StartDate = new DateTime(2018, 07, 11, 15, 00, 00);
            appointment5.FinishDate = new DateTime(2018, 07, 11, 17, 00, 00);

            Appointment appointment6 = new Appointment();
            appointment6.StartDate = new DateTime(2018, 07, 11, 18, 00, 00);
            appointment6.FinishDate = new DateTime(2018, 07, 11, 19, 00, 00);

            appointments.Add(appointment1);
            appointments.Add(appointment2);
            appointments.Add(appointment3);
            appointments.Add(appointment4);
            appointments.Add(appointment5);
            appointments.Add(appointment6);

            Console.ReadLine();
        }
    }
    public class Appointment
    {
        public DateTime StartDate { get; set; }
        public DateTime FinishDate { get; set; }
    }

Upvotes: 2

Views: 1211

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

Let's sort the appointments and then Aggregate them: we have only 3 choices to implement:

  1. Appointments disjoint
  2. Appointment includes the next appointment
  3. Appointments overlap

Sample code:

  var total = appointments
    .OrderBy(appointment => appointment.StartDate)
    .Aggregate(new Tuple<double, DateTime?>(0.0, null), (acc, item) => {
      if (!acc.Item2.HasValue || acc.Item2.Value <= item.StartDate) // Disjoint
        return new Tuple<double, DateTime?>(
          acc.Item1 + (item.FinishDate - item.StartDate).TotalHours, 
          item.FinishDate);
      else if (acc.Item2.Value >= item.FinishDate) // Include
        return acc;
      else // Partially overlap
        return new Tuple<double, DateTime?>(
          acc.Item1 + (item.FinishDate - acc.Item2.Value).TotalHours,
          item.FinishDate);
    })
    .Item1;

 // 8
 Console.WriteLine(total);

Upvotes: 2

JuanR
JuanR

Reputation: 7783

One way to solve this would be to gather the hours that are covered by appointments, then group them.

You could add a method to the Appointment class to get the hours covered by the appointment:

public IEnumerable<int> GetHours()
{
    List<int> hours = new List<int>();
    var startDate = StartDate;
    var finishDate = FinishDate;
    while(startDate < finishDate)
    {
        hours.Add(startDate.Hour);
        startDate = startDate.AddHours(1);
    }
    return hours;
}

You can then group them:

var result = appointments.SelectMany(a => a.GetHours()).GroupBy(i => i);

Console.WriteLine("Total hours: {0}", result.Count()); //This is the count
foreach (var hour in result)
{
    Console.WriteLine("{0} => {1}", hour.Key, hour.Count());
}

Output in console:

Total hours: 8
8 => 1
9 => 2
10 => 3
11 => 2
14 => 1
15 => 2
16 => 1
18 => 1

Upvotes: 1

Cetin Basoz
Cetin Basoz

Reputation: 23797

You first need to merge the overlapping times and then sum the timespan:

void Main()
{
List<Appointment> appointments = new List<Appointment>();

            Appointment appointment1 = new Appointment();
            appointment1.StartDate = new DateTime(2018, 07, 11, 08, 00, 00);
            appointment1.FinishDate = new DateTime(2018, 07, 11, 11, 00, 00);

    Appointment appointment2 = new Appointment();
    appointment2.StartDate = new DateTime(2018, 07, 11, 10, 00, 00);
    appointment2.FinishDate = new DateTime(2018, 07, 11, 12, 00, 00);

    Appointment appointment3 = new Appointment();
    appointment3.StartDate = new DateTime(2018, 07, 11, 09, 00, 00);
    appointment3.FinishDate = new DateTime(2018, 07, 11, 12, 00, 00);

    Appointment appointment4 = new Appointment();
    appointment4.StartDate = new DateTime(2018, 07, 11, 14, 00, 00);
    appointment4.FinishDate = new DateTime(2018, 07, 11, 16, 00, 00);

    Appointment appointment5 = new Appointment();
    appointment5.StartDate = new DateTime(2018, 07, 11, 15, 00, 00);
    appointment5.FinishDate = new DateTime(2018, 07, 11, 17, 00, 00);

    Appointment appointment6 = new Appointment();
    appointment6.StartDate = new DateTime(2018, 07, 11, 18, 00, 00);
    appointment6.FinishDate = new DateTime(2018, 07, 11, 19, 00, 00);

    appointments.Add(appointment1);
    appointments.Add(appointment2);
    appointments.Add(appointment3);
    appointments.Add(appointment4);
    appointments.Add(appointment5);
    appointments.Add(appointment6);

    var ranges = appointments.Select(a => new Range {Start=a.StartDate, End=a.FinishDate});
    var total = MergeTimes(ranges).Sum(a => (a.End-a.Start).TotalHours);
    Console.WriteLine(total);
}

public class Appointment
{
    public DateTime StartDate { get; set; }
    public DateTime FinishDate { get; set; }

}

public class Range
{
    public DateTime Start {get;set;}
    public DateTime End {get;set;}
}

public IEnumerable<Range> MergeTimes(IEnumerable<Range> times)
{
    if (times.Count() == 0)
    {
        return times;
    }
    Range[] orderedTimes = (from t in times
                            orderby t.Start
                            select t).ToArray();
    List<Range> merged = new List<Range>();
    Range current = new Range
    {
        Start = orderedTimes[0].Start,
        End = orderedTimes[0].End
    };
    for (int i = 0; i < orderedTimes.Length; i++)
    {
        if (current.Start <= orderedTimes[i].End && current.End >= orderedTimes[i].Start)
        {
            current.Start = ((current.Start < orderedTimes[i].Start) ? current.Start : orderedTimes[i].Start);
            current.End = ((current.End > orderedTimes[i].End) ? current.End : orderedTimes[i].End);
        }
        else
        {
            merged.Add(new Range
            {
                Start = current.Start,
                End = current.End
            });
            current = new Range
            {
                Start = orderedTimes[i].Start,
                End = orderedTimes[i].End
            };
        }
    }
    merged.Add(new Range
    {
        Start = current.Start,
        End = current.End
    });
    return merged;
}

Upvotes: 2

Davy
Davy

Reputation: 6441

Are you aware of the properties on the TimeSpan class?

(dateA - dateB).TotalMinutes

https://msdn.microsoft.com/en-us/library/system.timespan.totalminutes.aspx

Upvotes: 1

Related Questions