What does 'P' stand for in the DateInterval format?

Consider the following example quoted from php manual for DateTime

<?php
  $date = new DateTime('2000-01-20');
  $date->sub(new DateInterval('P10D'));
  echo $date->format('Y-m-d') . "\n";
?>

'D' is for days, what does the 'P' stand for in that formatting?


From the manual

Interval specification.

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.


'P' stands for Period. see here http://php.net/manual/en/dateinterval.construct.php


I think it can be answered in more details. First of all, DateInterval constructor method takes one parameter named $interval_spec which is string.

DateInterval::__construct ( string $interval_spec )

This parameter has a specification described as below:

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.

There are some Period Designators that are used in the argument:

  • Y for years
  • M for months
  • D for days
  • W for weeks. These get converted into days, so can not be combined with D.
  • H for hours
  • M for minutes
  • S for seconds

Let's see some example using Period Designators:

  • Two days is P2D.
  • Two seconds is PT2S.
  • Six years and five minutes is P6YT5M.

There is an order that needs to be maintained as described the doc:

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, not P4D1Y.

The specification can also be represented as a datetime.

  • One year, two months, four days would be P0001-02-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).