PHP 5.3 DateTime for recurring events

I have a calendar application that uses the new PHP DateTime classes. I have a way that I handle recurring events, but it seems to be a hack, and I wanted to see if you guys have any better ideas:

  • I have a recurring event that starts on 11/16/2009 (November 16, 2009)
  • This will happen every 3 days.
  • The event will be repeated endlessly.

Let's say a user watches a calendar for December 3100 - this event should show that it repeats every 3 days, as usual. The question is, how can I calculate those days this month?

===========================================

This is how I do it mostly, but I know that I am missing something simpler:

  • I calculate the difference in days between the beginning of the month (December 1, 3100) and the start date of the event (November 16, 2009) stored as $ daysDiff
  • I subtract the module, so I get a 3-day coefficient from the very beginning as follows: $ daysDiff - ($ daysDiff% 3)
  • As an argument, you can say that gives me November 29, 3100 as a date.
  • Then I add 3 days to this date until I have all the dates for December 31st.

My main problem is step 1. The PHP function DateInterval :: date_diff does not calculate the difference in days. It will give me years, months and days. Then I have to push the numbers to get a date estimate around December 31st. 11/16/2009 + (1090 years * 365.25 days) + (9 months * 30.5 days) + 15 days

, 9999, , , , .

+3
2

unix, , , 3 . , :

$startDate = new DateTime(20091116);
$startTimestamp = $startDate->format('u');
$recursEvery = 259200; // 60*60*24*3 = seconds in 3 days

// find the first occurrence in the selected month (September)
$calendarDate = new DateTime(31000901); // init to Sept 1, 3100
while (0 != (($calendarDate->format('u') - $startTimestamp) % $recursEvery)) {
    $calendarDate->modify('+1 day');
}

$effectiveDates = array();
while ($calendarDate->format('m') == 9) {
    $effectiveDates[] = clone $calendarDate;
    $calendarDate->modify('+3 day');
}

//$effectiveDates is an array of every date the event occurs in September, 3100.

, , , . , , DateTimes , , 00:00:00, while . , .

+3

, DatePeriod Iterator, filterd , :

<?php
class DateFilterIterator extends FilterIterator {
    private $starttime;
    public function __construct(Traversable $inner, DateTime $start) {
        parent::__construct(new IteratorIterator($inner));
        $this->starttime = $start->getTimestamp();
    }
    public function accept() {
        return ($this->starttime < $this->current()->getTimestamp());
    }
}

$db = new DateTime( '2009-11-16' );
$de = new DateTime( '2020-12-31 23:59:59' );
$di = DateInterval::createFromDateString( '+3 days' );
$df = new DateFilterIterator(
    new DatePeriod( $db, $di, $de ),
    new DateTime( '2009-12-01') );

foreach ( $df as $dt )
{
    echo $dt->format( "l Y-m-d H:i:s\n" );
}
?>
+9

Source: https://habr.com/ru/post/1723150/


All Articles