• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • DateInterval::__construct()

    (PHP 5 >= 5.3.0, PHP 7)

    Creates a new DateInterval object

    说明

    publicDateInterval::__construct(string $interval_spec)

    Creates a new DateInterval object.

    参数

    $interval_spec

    An interval specification.

    The format starts with the letterP,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.

    $interval_specPeriod Designators
    Period DesignatorDescription
    Yyears
    Mmonths
    Ddays
    Wweeks. These get converted into days, so can not be combined withD.
    Hhours
    Mminutes
    Sseconds

    Here are some simple examples. Two days isP2D. 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 asP1Y4D,notP4D1Y.

    The specification can also be represented as a date time. A sample of one year and four days would beP0001-00-04T00:00:00. But the values in this format can not exceed a given period's roll-over-point (e.g.25hours is invalid).

    These formats are based on the» ISO 8601 duration specification.

    错误/异常

    Throws anExceptionwhen the$interval_speccannot be parsed as an interval.

    范例

    Example #1DateIntervalexample

    <?php
    $interval = new DateInterval('P2Y4DT6H8M');
    var_dump($interval);
    ?>
    

    以上例程会输出:

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

    参见

    • DateInterval::format() Formats the interval
    • DateTime::add() 给一个 DateTime 对象增加一定量的天,月,年,小时,分钟以及秒。
    • DateTime::sub() 对一个 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。
    • DateTime::diff() Returns the difference between two DateTime objects
    M is used to indicate both months and minutes.
    As noted on the referenced wikipedia page for ISO 6801 http://en.wikipedia.org/wiki/Iso8601#Durations
    To resolve ambiguity, "P1M" is a one-month duration and "PT1M" is a one-minute duration (note the time designator, T, that precedes the time value).
    Using: PHP 5.3.2-1ubuntu4.19
    // For 3 Months
    $dateTime = new DateTime;echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
    $dateTime->add(new DateInterval("P3M"));
    echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
    Results in:
    2013-07-11T11:12:26-0400
    2013-10-11T11:12:26-0400
    // For 3 Minutes
    $dateTime = new DateTime;echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
    $dateTime->add(new DateInterval("PT3M"));
    echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
    Results in:
    2013-07-11T11:12:42-0400
    2013-07-11T11:15:42-0400
    Insert a T after the P in the interval to add 3 minutes instead of 3 months.
    Note that, while a DateInterval object has an $invert property, you cannot supply a negative directly to the constructor similar to specifying a negative in XSD ("-P1Y"). You will get an exception through if you do this. 
    Instead you need to construct using a positive interval ("P1Y") and the specify the $invert property === 1.
    I think it is easiest if you would just use the sub method on the DateTime class.
    <?php
    $date = new DateTime();
    $date->sub(new DateInterval("P89D"));
    As previously mentioned, to do a negative DateInterval object, you'd code: 
    <?php
    $date1 = new DateTime();
    $eightynine_days_ago = new DateInterval( "P89D" );
    $eightynine_days_ago->invert = 1; //Make it negative. 
    $date1->add( $eightynine_days_ago );
    ?>
    and then $date1 is now 89 days in the past.
    Alternatively you can use DateInterval::createFromDateString() for negative intervals:
    <?php
    $date = new DateTime();
    $date->add(DateInterval::createFromDateString('-89 days'));
    Warning - despite the $interval_spec accepting the ISO 8601 specification format, it does not accept decimal fraction values with period or comma as stated in the specification.
    https://bugs.php.net/bug.php?id=53831
    <?php
    /* Example from ISO 8601 documentation */
    $interval = new DateInterval('P0.5Y');
    ?>
    Will result in
    Fatal error: Uncaught exception 'Exception' with message 'DateInterval::__construct(): Unknown or bad format (P0.5Y)'
    It should be noted that this class will not calculate days/hours/minutes/seconds etc given a value in a single denomination of time. For example:
    <?php
      $di = new DateInterval('PT3600S');
      echo $di->format('%H:%i:%s');
      
    ?>
    will yield 0:0:3600 instead of the expected 1:0:0
    It is not stated, but you cannot create directly a negative interval, this is you cannot create a "-2 days" interval as:
    <?
    $interval = new DateInterval("P-2D");//or
    $interval = new DateInterval("-P2D");
    ?>
    Instead you have to create first the interval and then set its 'invert' property to 1, this is:
    <?
    $interval = new DateInterval("P2D");
    $interval->invert = 1;
    ?>
    Then you should keep in mind that this interval acts as a negative number, hence to subtract the interval from a given date you must 'add' it:
    <?
    $interval = new DateInterval("P2D");
    $interval->invert = 1;
    $date    = new DateTime ("1978-01-23 17:46:00");
    $date->add($interval)->format("Y-m-d H:i:s");//this is "1978-01-21 17:46:00"
    ?>
    
    Take care, if you have a DateTime Object on the 31h of January and add Da DateInterval of one Month, then you are in March instead of February.
    For Example:
    ---
    // given the actual date is 2017-01-31
    $today = new DateTime('now', $timeZoneObject);
    $today->add(new DateInterval('P1M'));
    echo $today->format('m');
    // output: 03
    ---
    Although PHP refers to periods of time as "intervals", ISO 8601 refers to them as "durations". In ISO 8601, "intervals" are something else.
    While ISO 8601 allows fractions for all parts of a duration (e.g., "P0.5Y"), DateInterval does not. Use caution when calculating durations. If the duration has a fractional part, it may be lost when storing it in a DateInterval object.
    ⚠️ It's important to remember the warning about DateInterval given by "admin at torntech dot com" in an earlier comment (http://php.net/manual/en/dateinterval.construct.php#116750). To reiterate:
    Some versions of PHP (e.g., 5.6.31) have a bug that disallows fractional parts in a ISO 8601 duration string given as the argument for the DateInterval constructor. That is, these examples will fail:
    <?php
    // 'P0.5Y' is valid according to ISO 8601
    $interval = new DateInterval('P0.5Y'); // Throws exception
    ?>
    <?php
    // 'PT585.829S' is valid according to ISO 8601
    $interval = new DateInterval('PT585.829S'); // Throws exception
    ?>
    If this bug affects you, please go to the report for this bug in the PHP Bug Tracking System, and place a vote stating that it affects you: https://bugs.php.net/bug.php?id=53831
    To recover the interval specification string:
    <?php
    function get_interval_spec(DateTime $alpha, DateTime $omega)
    {
      $intvl = $alpha->diff($omega);
      $date = NULL;
      if ($intvl->y) $date .= $intvl->y . 'Y';
      if ($intvl->m) $date .= $intvl->m . 'M';
      if ($intvl->d) $date .= $intvl->d . 'D';
      $time = NULL;
      if ($intvl->h) $time .= $intvl->h . 'H';
      if ($intvl->i) $time .= $intvl->i . 'M';
      if ($intvl->s) $time .= $intvl->s . 'S';
      if ($time) $time = 'T' . $time;
      $text ='P' . $date . $time;
      if ($text == 'P') return 'PT0S';
      return $text;
    }
    interval_spec Period Designators, has two 'M's for months and minutes.