PHP DateInterval __construct() Method
The PHP DateInterval::__construct() method creates a new DateInterval object.
Syntax
public DateInterval::__construct(duration)
Parameters
duration |
Required. Specify an interval. The format starts with the letter P, for period. Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T. The duration Period designators are:
|
Note: The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. Hence, years before months, months before days, days before minutes, etc. Therefore, one year and four days must be represented as P1Y4D, not P4D1Y.
Return Value
Returns a new DateInterval object on success.
Exceptions
Throws Exception if the duration cannot be parsed as an interval.
Example: creating DateInterval object
The example below shows the usage of DateInterval::__construct() method.
<?php //creating a DateInterval object $interval = new DateInterval('P1W2D'); //displaying the result print_r($interval); ?>
The output of the above code will be:
DateInterval Object ( [y] => 0 [m] => 0 [d] => 9 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
Example: using DateInterval object
The DateInterval object can be used to modify a given DateTime object. Consider the example below:
<?php //creating a DateTime object $date = new DateTime("10-May-2015"); //displaying the date echo "Original Date: ".$date->format('d-M-Y')."\n"; //creating a DateInterval object //1 year 2 months 15 days $interval = new DateInterval('P1Y2M15D'); //adding the date interval to the date $date->add($interval); //displaying the result echo "Modified Date: ".$date->format('d-M-Y')."\n"; ?>
The output of the above code will be:
Original Date: 10-May-2015 Modified Date: 25-Jul-2016
❮ PHP Date and Time Reference