Yona
Yona

Reputation: 9682

Determine if a day of week and time fall in a custom weekend period

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.

Upvotes: 0

Views: 587

Answers (3)

Rex Kerr
Rex Kerr

Reputation: 167891

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

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273244

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)

Upvotes: 1

John Feminella
John Feminella

Reputation: 311526

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.

Upvotes: 0

Related Questions