php - 重复月度和年度事件——如何保证准确性?

标签 php calendar strtotime recurring-events

我目前允许在我的日历应用程序(使用 fullCalendar)上每天或每周重复事件。

我的 View 有一个激活两个下拉列表的复选框:一个用于重复间隔(每天、每周),另一个用于频率(一次、两次等)。

$evt_interval_options = array( //this will be $row->interval in the model
    '86400' => 'Daily',   
    '604800' => 'Weekly'; 

$evt_frequency_options = array(  //this will be //$i in the model
    '1' => '2',    
    '2' => '3',    

<?php echo form_checkbox('evt_repeat', 'FALSE', FALSE, 'class="repeat_checkbox"'); 
      echo form_dropdown('evt_interval', $evt_interval_options');
      echo form_dropdown('evt_frequency', $evt_frequency_options'); ?>

这最终到达我的模型,它运行一个循环来检查事件是否应该重复——如果是,它将考虑间隔 ($row->interval) 和频率 ($i).

$cal_data[] = array(
    'start' => strtotime($row->date_1 . ' ' . $row->time_1) + ($i ? ($row->interval * $i) : 0),
);

这可以很好地显示基于数据库中单个记录条目的多个每日或每周事件。

问题在于每月和每年。因为这些将有可变的秒数,因为

03/01/2011 00:00:00 --> 04/01/2011 00:00:00 ===> 2674800 seconds
04/01/2011 00:00:00 --> 05/01/2011 00:00:00 ===> 2592000 seconds
and so on for monthly and yearly differences

那么我该如何解决这个问题呢?是否有任何功能或 strtotime 命令可以帮助准确指示每月应在例如4th 还是应该在 7 月 4 日 重复?

我使用的是 PHP 5.2.14。

最佳答案

感谢所有回答者 - 我通过来自 PHP.net manual on strtotime()@akniep 解决了这个函数的问题.

function get_x_months_to_the_future( $base_time = null, $months = 1 )
{
    if (is_null($base_time))
        $base_time = time();

    $x_months_to_the_future    = strtotime( "+" . $months . " months", $base_time );

    $month_before              = (int) date( "m", $base_time ) + 12 * (int) date( "Y", $base_time );
    $month_after               = (int) date( "m", $x_months_to_the_future ) + 12 * (int) date( "Y", $x_months_to_the_future );

    if ($month_after > $months + $month_before)
        $x_months_to_the_future = strtotime( date("Ym01His", $x_months_to_the_future) . " -1 day" );

    return $x_months_to_the_future;
}

这样做是为了解决每月 29、30、31 以及 2 月 28 日 重复发生的事件的问题。

我喜欢这个功能,因为它从日历应用的视角解决了我的问题。

如果用户请求从 1 月 31 日开始的每月重复事件,正常 strtotime 将在 2 月和没有 31 天的任何其他月份表现不稳定。

正如我在上面的评论中指出的那样,Google 日历通过跳过没有此类日期的月份来解决这个问题有点奇怪。

我想这是一个偏好问题,但对我来说,将重复事件放在该月的最后一天更有意义 - 因此在 Jan 31 示例中,重复事件将会发生2 月 28 日 3 月 31 日 4 月 30 日 等等。

我将这个函数放在一个循环中,该循环迭代用户请求的重复次数并且它完美地工作。它在年度事件中也能很好地工作,因为我只是将 12 作为月数传递。

关于php - 重复月度和年度事件——如何保证准确性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5942005/

相关文章:

javascript - 选择日历日期并更新链接标签

php - strtotime 使用日期输入

php - 使用 PhpSpreadsheet 从字符串创建 CSV 文件

php - 在 Powerpoint 中插入来自 MySQL 或 PHP 的数据

PHP header 位置不起作用 - Wordpress 中的移动重定向脚本

java - 在控制台中打印公历

php - 禁用输入字段中的 html 标签、php、脚本

jquery - 没有时间段的 Xpages 日历

php - 添加日期变量

php strtotime 反转