DateInterval::__construct
(PHP 5 >= 5.3.0, PHP 7)
DateInterval::__construct — Creates a new DateInterval object
Description
$duration
)Creates a new DateInterval object.
Parameters
-
duration
-
An interval specification.
The format starts with the letter
P
, forperiod.
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 letterT
.duration
Period DesignatorsPeriod Designator Description Y
years M
months D
days W
weeks. These get converted into days, so can not be combined with D
.H
hours M
minutes S
seconds Here are some simple examples. Two days is
P2D
. Two seconds isPT2S
. Six years and five minutes isP6YT5M
.Note:
The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as
P1Y4D
, notP4D1Y
.The specification can also be represented as a date time. A sample of one year and four days would be
P0001-00-04T00:00:00
. But the values in this format can not exceed a given period's roll-over-point (e.g.25
hours is invalid).These formats are based on the » ISO 8601 duration specification.
Errors/Exceptions
Throws an Exception when the duration
cannot be parsed as an interval.
Examples
Example #1 DateInterval example
<?php $interval = new DateInterval('P2Y4DT6H8M'); var_dump($interval); ?>
The above example will output:
object(DateInterval)#1 (8) { ["y"]=> int(2) ["m"]=> int(0) ["d"]=> int(4) ["h"]=> int(6) ["i"]=> int(8) ["s"]=> int(0) ["invert"]=> int(0) ["days"]=> bool(false) }
See Also
- DateInterval::format() - Formats the interval
- DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
- DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
- DateTime::diff() - Returns the difference between two DateTime objects
© 1997–2020 The PHP Documentation Group
Licensed under the Creative Commons Attribution License v3.0 or later.
https://www.php.net/manual/en/dateinterval.construct.php