views:

133

answers:

3

I've been trying to come up with a method, that given a day of week and time of day, it will return if it falls under a custom weekend period.

The weekend period is saved in 4 variables as follows:

  1. The day of week when it starts (0-6)
  2. The time of day when it starts (0-23)
  3. The day of week when it ends (0-6)
  4. The time of day when it ends (0-23)

Based on these fields, the weekend period can be anything the user selected (even if it is well beyond a regular weekend)

I've been banging this one for awhile but to no avail. I'm trying this in delphi but any language will do, as I'm looking for the algorithm and not the implementation.

+1  A: 

I assume there is also a constraint that the endpoint is >= beginpoint.

The easiest ways is to normalize to 'hours since week started'.

double interest = day * 24 + hours;
double startWeekend = startDay * 24 + startHours;
double endWeekend = endDay * 24 + endHours.
bool isInWeekend = interest >= startWeekend && interest < endWeekend;

Adjust <= and >= as desired.

Edit:

if the problem is that a Weekend could overlap the 7 * 24 hour boundary then it gets a little more interesting:

if startWeekend < endWeekend
then isInWeekend = interest >= startWeekend AND interest < endWeekend;
else isInWeekend = interest >= startWeekend OR interest < endWeekend;

(slightly mixed C / Pascal pseudo code)

Henk Holterman
Why do I need a constraint? It is not an endpoint, it's a day of week.
Y Low
I count sunday as 0. So, saturday -> sunday is 6 -> 0 to me.
Alex Bagnolini
And a day-of-week + time-of-day is a point in time.
Henk Holterman
Selecting a weekend period Friday(17:00) -> Monday(9:00) will yield 5,17 -> 1,9Why is this not valid?
Y Low
I was already editing that in. And fixed a typo.
Henk Holterman
A: 

Call these four values dstart, dend for the day and hstart, hend for the hours. Then consider the total number of hours since day 0, hour 0, which is given by t_start = dstart * 24 + hstart, and likewise for t_end.

If the hour of the week that you're currently in is before t_end or after t_start, you're in the weekend period.

John Feminella
Did you mean: "before t_end *and* after t_start"? Which I would phrase as "after t_start and before t_end".
Software Monkey
A: 

If you want to handle intervals that wrap,

double hstart = startDay*24 + startHour;
double hend = endDay*24 + endHour;
double htest = testDay*24 + testHour;
return (hend-hstart)*(htest-hstart)*(hend-htest) > 0
Rex Kerr