C# does not include anything for this out of the box, but you could try something like this:
public DateTime? GetLatestOpen(DateTime current)
{
var openHours = ...collection of pairs of int (Day) and two date times (TimeRange[])...
if (!openHours.Any()) { return null; } //prevent inf. loop if no open hours ever
var currentDay = current.DayOfWeek;
var hoursToday = openHours.FirstOrDefault(oh => oh.DayOfWeek == currentDay);
if (hoursToday != null)
{
var currentTime = current.TimeOfDay();
if (currentTime >= hoursToday.TimeRange[0] &&
currentTime <= hoursToday.TimeRange[1])
{
return currentTime;
}
else
{
return hoursToday.TimeRange[1];
}
}
return GetLatestOpen(current.AddDays(-1));
}
...
var latestOpen = GetLatestOpen(DateTime.Now);
...
Your openHours
collection would look something like the following (I used an anonymous type for simplicity of the example):
var openHours = new [] { new { Day = 1, TimeRange = new DateTime[] { ...Open..., ...Close...} }, new { Day = 2...... } };
Notes:
A couple things to note about the above:
Day = 0
is Sunday,Day = 1
is Monday ....Day = 6
is Saturday- You can use another type of collection for the
TimeRange
, if you want - For the
...Open...
and...Close...
DateTime
objects, you need not worry about the actual Date; you only carry about the Time portion
Let me know if you have any questions on this. I hope this helps! Good luck, and happy coding! :)