【问题标题】:Finding how many times an event occur within a time period找出一个事件在一个时间段内发生了多少次
【发布时间】:2022-02-16 00:40:43
【问题描述】:

对不起,如果标题令人困惑,我会尽力解释得更好。

假设每 n 周发生一次事件。 当用户输入所选日期时,我想计算从现在到所选日期之间此事件发生的次数。活动的日期是固定的(不受用户影响)。

我可以找到两个特定日期之间的事件数,例如:

$eventstart = strtotime("2021-10-18");
$chosenday = strtotime("2021-12-24");                   /// let's imagine the user chose this day
$event = 0;

    for ($i=$eventstart; $i<=$chosenday; $i+=1209600)  /// for example : every two weeks
    {
        $event++;
    }

echo "The event occurs " . $event . " times.";  

这很好用,只是开始日期与其中一个事件相同,我需要将开始日期设为“现在”(同时保持事件的日期固定)。

我试图将这段代码放在一些“while”或“for”循环之间,但正如预期的那样,它不起作用。我真的应该在另一个时间间隔内吗?

我希望这是有道理的,提前谢谢你。

【问题讨论】:

  • 无论用户选择什么开始日期,您都必须从事件发生的第二天开始计算。但既然你没有告诉我们这个神秘事件何时发生的规则,我们无法帮助你。例如,该事件是否总是在每隔一个星期一发生?每月 1 号和 15 号?还有什么?
  • "the start date is the same as one of the event, and I need the start date to be "now" (while keeping the events' day fixed)." - 你能不能试着澄清一下这实际上意味着什么,因为我正在努力解决这个问题。另外 - 对于上述内容,您期望的输出是什么?
  • @kmoser 该事件每三周发生一次(所以我不能仅仅制定一个规则让它在每个月的第一天计算一次)。
  • @ProfessorAbronsius 抱歉,我对措辞不是很清楚。例如,假设事件发生在 10 月 18 日,之后每三周发生一次。用户输入圣诞节。我想知道从现在到圣诞节期间该事件发生了多少次。 (所以 10 月 18 日、11 月 1 日、11 月 22 日等到圣诞节 24 日)是不是更清楚了?
  • 您对给出的数据有何期望? 5个还是6个还是其他?

标签: php


【解决方案1】:

这应该会给你你需要的答案:

define( 'EVENT_INTERVAL_DAYS', 21 ); // Every 3 weeks

$event_start = new DateTime("2021-10-13"); // When the repeating event starts

$range_start = new DateTime("today midnight"); // Important: must include midnight so time is 00:00:00!

$end = new DateTime("2021-12-31"); // End of range to test

$first_occurrence = clone($range_start);

// Determine how many days to move $first_occurrence forward to actual first occurrence of event:
$diff = $first_occurrence->diff($event_start)->format("%a") % EVENT_INTERVAL_DAYS;

// Move $first_occurrence forward to first instance of event:
$first_occurrence->add(new DateInterval('P' . $diff . 'D' ));

// Determine how many times event occurs between $first_occurrence and $end:
$diff_occurrences = ( $first_occurrence->diff($end)->format("%a") + 1 ) / EVENT_INTERVAL_DAYS;

// Determine number of occurrences:
$n = ceil( $diff_occurrences );

echo "Between " . $range_start->format('Y-m-d') . ' and ' . $end->format('Y-m-d') . ", event occurs $n time(s)\n";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    相关资源
    最近更新 更多