Search code examples
c#datetimeintervalsdifferencetimespan

How to delete a particular time slot, from the difference between two dates


string StartDateString = "2020-04-20 18:05:07.6187";
DateTime StartDate = DateTime.Parse(StartDateString);

string EndDateString = "2020-04-22 14:10:00.6187";
DateTime EndDate = DateTime.Parse(EndDateString);

TimeSpan DifferenceStartDateEndDate = StartDate - EndDate;

Now I want to delete time between 10 pm to 8am from DifferenceStartDateEndDate (1 day 20 hours four minutes). I.e. I want to remove time between 10 pm to 8 am which will occur from StartDate to EndDate.


Solution

  • As I understand it, you need to add to your calculation only hours in a day during which your business is active. (08:00 - 22:00)

    Here are two helpers:

    // For the first day in our calculation
    // Start at 08:00 if the given date has an hour component that is earlier
    static TimeSpan GetTill2200(DateTime date)
    {
        if (date.Hour >= 22) return TimeSpan.Zero;
        if (date.Hour < 8) date = date.Date.AddHours(8);
        return date.Date.AddHours(22) - date;
    }
    
    // For the last day in our calculation
    // End at 22:00 if the given date has an hour component that is later
    static TimeSpan GetFrom0800(DateTime date)
    {
        if (date.Hour < 8) return TimeSpan.Zero;
        if (date.Hour >= 22) date = date.Date.AddHours(22);
        return date - date.Date.AddHours(8);
    }
    

    And here is the code flow to combine start and end dates and the dates in the middle

    // StartDate and EndDate variables as in your question.
    
    TimeSpan result = GetTill2200(StartDate);
    
    DateTime currentDate = StartDate.AddDays(1);
    while (currentDate.Date < EndDate.Date)
    {
        // Add 14 hours
        // Total: 17:54:52:3813
        result = result.Add(TimeSpan.FromHours(14));
        currentDate = currentDate.AddDays(1);
    }
    
    // returns 06:10:00.6187
    // Total = 1.00:04:53 ( 1 days, 4 minutes, 53 seconds )
    result = result.Add(GetFrom0800(EndDate));
    
    // Prints 1.00:04:53
    Console.WriteLine(result);