95

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Shrinath
  • 7,888
  • 13
  • 48
  • 85

3 Answers3

131

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.

Community
  • 1
  • 1
Phil
  • 157,677
  • 23
  • 242
  • 245
26

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

Java
  • 2,451
  • 10
  • 48
  • 85
  • 15
    That's crazy, so many examples use `P` but that reference is so understated. I guessed it meant period and I was searching `php.net` for that word, I obviously never got to the constructor page.. But it's not referenced on `date_format`, `DateTime::diff`, `DateTime::format`, `DateInterval`, and a host of general `Date/Time` functions. I wanted to know if there were any other prefixes to know about and be damned if I could find it til I came to stack exchange – Madivad Sep 23 '17 at 11:37
17

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).

unclexo
  • 3,691
  • 2
  • 18
  • 26