PHP Function Reference

PHP DatePeriod __construct() Method



The PHP DatePeriod::__construct() method creates a new DatePeriod object.

Syntax

public DatePeriod::__construct(start, interval, 
                        recurrences, options)
public DatePeriod::__construct(start, interval, 
                        end, options)
public DatePeriod::__construct(isostr, options)

Parameters

start Required. Specify the start date of the period.
interval Required. Specify the interval between recurrences within the period.
recurrences Required. Specify the number of recurrences. Must be greater than 0.
end Required. Specify the end date of the period.
isostr Required. Specify an ISO 8601 repeating interval specification. Zero occurrences (R0/) are not supported.
options Optional. Can be set to DatePeriod::EXCLUDE_START_DATE to exclude the start date from the set of recurring dates within the period.

Return Value

Returns a new DatePeriod object.

Example: creating DatePeriod object

The example below shows the usage of DatePeriod::__construct() method.

<?php
$start = new DateTime('2015-10-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2015-10-31');
$recurrences = 4;
$iso = 'R4/2015-10-01T00:00:00Z/P7D';

//all of these periods are equivalent.
$period = new DatePeriod($start, $interval, $recurrences);
$period = new DatePeriod($start, $interval, $end);
$period = new DatePeriod($iso);

//iterating over the DatePeriod object, to display 
//all the recurring dates within the period
foreach ($period as $date) {
  echo $date->format('d-M-Y')."\n";
}
?>

The output of the above code will be:

01-Oct-2015
08-Oct-2015
15-Oct-2015
22-Oct-2015
29-Oct-2015

Example: excluding the start date

By setting DatePeriod::EXCLUDE_START_DATE, we can exclude the start date from the set of recurring dates within the period.

<?php
$start = new DateTime('2015-10-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2015-10-31');

$period = new DatePeriod($start, $interval, $end,
                         DatePeriod::EXCLUDE_START_DATE);

//iterating over the DatePeriod object, to display 
//all the recurring dates within the period 
//the start date 01-Oct-2015 is excluded
foreach ($period as $date) {
  echo $date->format('d-M-Y')."\n";
}
?>

The output of the above code will be:

08-Oct-2015
15-Oct-2015
22-Oct-2015
29-Oct-2015

❮ PHP Date and Time Reference