Reputation: 33
I'm trying to write a function which can check if a shop is open, but it doesn't work if the closing time is in the next day.
For example, it works if the the shop is open from 16:00 - 21:00, but not for 16:00 - 1:00.
For these open times:
Sunday Open - Yes
Sunday Start - 16:00
SundayEnd - 01:00
Open Monday - Yes
Open Monday - 16:00
MondayEnd - 01:00
If it is Monday 00:30, the function must return true, but that does not succeed.
My code now:
OpenHours oh = GetOpenHours();
DateTime now = DateTime.Now;
bool todayOpen = GetOpenDay(oh, now.DayOfWeek);
TimeSpan end = GetOpenEnd(oh, now.DayOfWeek);
TimeSpan begin = GetOpenStart(oh, now.DayOfWeek);
if (end < begin)
return todayOpen && (now.TimeOfDay < end || now.TimeOfDay > begin);
else
return todayOpen && (now.TimeOfDay < end && now.TimeOfDay > begin);
How can I make this work?
Upvotes: 1
Views: 1306
Reputation: 247153
I would suggest using the begin time and end time to calculate a duration (TimeSpan) for how long the shop will be Open.
That way you can calculate the proper closing time based on the opening time and compare them to the current time to get your answer.
OpenHours oh = GetOpenHours();
DateTime now = DateTime.Now;
bool todayOpen = GetOpenDay(oh, now.DayOfWeek);
TimeSpan begin = GetOpenStart(oh, now.DayOfWeek);
TimeSpan end = GetOpenEnd(oh, now.DayOfWeek);
//Calculate duration
TimeSpan duration = end < begin? (TimeSpan.FromHours(24) - begin) + end : end - begin;
//calculate opening time using begin
DateTime openingTime = DateTime.Today.Add(begin);
//calculate closing time based on opening time and duration
DateTime closingTime = openTime.Add(duration);
return todayOpen && (openingTime <= now && now < closingTime);
Upvotes: 2