0

有人可以帮我弄清楚如何获得当前一周是否在事件中。

我有以下变量: start_date , end_date , current_date week_occurrence 。

我有一个返回发生次数的函数

// will return the number of weeks between start - end
function get_weeks_count($start , $end) {
       return floor(abs(strtotime($start) - strtotime($end)) / 604800);    
    }

现在我必须知道当前日期是否有效。

我有一个发生 = 每 N 周的条目。如何知道 N 是有效的。

不那么抽象:如果我们在 12 月并且每 3 周发生一次,则 start_date 是第 1 天,end_date 是 12 月 30 日)

它将返回:

 TRUE  for 1st week

 FALSE for the second week

 FALSE for the third week

 TRUE  for the last week
4

2 回答 2

0

这是我解决问题的方法 - 这适用于每 $n 周发生一次。

$n = $week_occurrence;
$occurrence = false;

// To begin, get the number of weeks between the start and current dates.
$weeks = get_weeks_count($start_date , $current_date); // Using the function you already have

// Now check if $weeks == 0
if ($weeks == 0) {
    $occurrence = true;

// If not, check if $weeks is divisible by $n without any remainder
} else if ($weeks % $n == 0) {
    $occurrence = true;
}

如果$occurrence仍然为假,则当前周不在正确的发生范围内,如果为真,则该周确实在范围内。

Effectively all we're doing here is checking that the current number of weeks since the start date is either equal to zero (we're still in the first week) or is divisible by the ocurrence without a remainder.

I hope this helps.

P.S. I've only answered the specific question that you asked. However, if you would like to know more about how this premiss could be used for scheduling etc., then feel free to ask and I'll expand on my answer accordingly

于 2012-12-07T15:47:36.640 回答
0

A combination of DateTime and DateInterval should help you achieve this easily.

function get_occurences(DateTime $start, DateTime $end, DateInterval $period) {
    $weeks = array();
    $cursor = clone $start;
    $rate = DateInterval::createFromDateString('1 week');
    do {
        /* We can check to see if it's within the occurrence period */
        if ($cursor == $start) {
            $isOccurrence = true;
            $start->add($period); // Move the start period up
        } else {
            $isOccurrence = false;
        }
        $weeks[$cursor->format('Y-m-d')] = $isOccurrence;
    } while($cursor->add($rate) < $end);
    return $weeks;
}

$period = DateInterval::createFromDateString('3 week');
$start = new DateTime('2012-12-01');
$end = new DateTime('2012-12-30');
/* From this array you can get both the number of occurrences as well as their respective dates*/
var_dump(get_occurences($start, $end, $period));

/** Output:

    array(5) {
      ["2012-12-01"]=>
      bool(true)
      ["2012-12-08"]=>
      bool(false)
      ["2012-12-15"]=>
      bool(false)
      ["2012-12-22"]=>
      bool(true)
      ["2012-12-29"]=>
      bool(false)
    }

*/
于 2012-12-07T15:52:59.607 回答