-2

I have a problem auto-detecting the start date and end date to store the day of the week, start time, and end time in DayBlock objects. Why do I need to auto-detect? Because startDate and endDate are selected by users. In the future, they cannot be hardcoded. I just know the hard-coded way like below:

//startDate = 22 Nov 2022 05:00 PM
//endDate = 25 Nov 2022 12:00 PM

class DayBlock
{
  public DayOfWeek DayOfWeek { get; set; }
  public TimeSpan Start { get; set; }
  public TimeSpan End { get; set; }
}

DayBlock[] blockWeekdays = {
new DayBlock {DayOfWeek=DayOfWeek.Tuesday, Start=TimeSpan.FromHours(17), End=TimeSpan.FromHours(24)},
new DayBlock {DayOfWeek=DayOfWeek.Wednesday, Start=TimeSpan.FromHours(0), End=TimeSpan.FromHours(24)},
new DayBlock {DayOfWeek=DayOfWeek.Thursday, Start=TimeSpan.FromHours(0), End=TimeSpan.FromHours(24)},
new DayBlock {DayOfWeek=DayOfWeek.Friday, Start=TimeSpan.FromHours(0), End=TimeSpan.FromHours(12)},
};

And how to include the hours and minutes in the DayBlock's timespans, because currently just can add hours in the time span, if the start time or end time includes minutes, how can I add them in the DayBlock?

I tried below the code but it doesn't work:

//startDate = 22 Nov 2022 05:30 PM
//endDate = 25 Nov 2022 1:15 PM

class DayBlock
{
  public DayOfWeek DayOfWeek { get; set; }
  public TimeSpan Start { get; set; }
  public TimeSpan End { get; set; }
}

DayBlock[] blockWeekdays = {
new DayBlock {DayOfWeek=DayOfWeek.Tuesday, Start=TimeSpan.FromHours(17:30), End=TimeSpan.FromHours(24)},
new DayBlock {DayOfWeek=DayOfWeek.Wednesday, Start=TimeSpan.FromHours(0), End=TimeSpan.FromHours(24)},
new DayBlock {DayOfWeek=DayOfWeek.Thursday, Start=TimeSpan.FromHours(0), End=TimeSpan.FromHours(24)},
new DayBlock {DayOfWeek=DayOfWeek.Friday, Start=TimeSpan.FromHours(0), End=TimeSpan.FromHours(13:15)},
};

I hope someone can help me solve the problem.

Fatt Sky
  • 650
  • 3
  • 11

1 Answers1

1

You may use a loop to iterate the days between startDate and endDate, creating a DayBlock object for each one. Here's an example:

DateTime startDate = new DateTime(2022, 11, 22, 17, 30, 0);
DateTime endDate = new DateTime(2022, 11, 25, 13, 15, 0);

if (endDate < startDate)
    throw new Exception("Bad input");

int days = (int)Math.Ceiling((endDate - startDate).TotalDays);
var blockWeekdays = new DayBlock[days];
for (int i = 0; i < days; i++)
{
    blockWeekdays[i] =
        new DayBlock
        {
            DayOfWeek = startDate.AddDays(i).DayOfWeek,
            Start = (i == 0 ? startDate.TimeOfDay : TimeSpan.Zero),
            End = (i == days - 1 ? endDate.TimeOfDay : TimeSpan.FromHours(24))
        };
}

This will also include the exact time of the DateTime (i.e., hours, minutes, seconds, milliseconds, etc.).