“ P”在日期间隔格式中代表什么?

考虑下面引自 日期时间的 php 手册的示例

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

“ D”代表天,“ P”在这种格式中代表什么?

63404 次浏览

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.

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