开发者

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

开发者 https://www.devze.com 2022-12-23 15:10 出处:网络
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.

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 algorith开发者_StackOverflow中文版m and not the implementation.


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)


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号