PHP.mk документација

DateInterval::__construct

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

dateinterval.construct.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека dateinterval.construct.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
DateInterval::__construct

Референца за `dateinterval.construct.php` со подобрена типографија и навигација.

dateinterval.construct.php

DateInterval::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::__constructКреира нов објект DateInterval

= NULL

public DateInterval::__construct(string $duration)

Креира нов објект DateInterval.

Параметри

duration

Спецификација на интервал.

Форматот започнува со буквата P, за period. Секој период на времетраење е претставен со цел број проследен со ознака на период. Ако времетраењето содржи временски елементи, тој дел од спецификацијата му претходи буквата T.

duration Ознаки на период
Ознака на период = NULL
Y years
M months
D days
W недели. Се претвора во денови. Пред PHP 8.0.0, не може да се комбинира со D.
H hours
M minutes
S seconds

Еве неколку едноставни примери. Два дена е P2D. Две секунди е PT2S. Шест години и пет минути е P6YT5M.

Забелешка:

Типовите на единици мора да се внесат од најголемата скала од лево до најмалата скала од десно. Значи години пред месеци, месеци пред денови, денови пред минути, итн. Така една година и четири дена мора да се претстават како P1Y4Dсега е исто како P4D1Y.

Спецификацијата може да се претстави и како датум и време. Пример за една година и четири дена би бил P0001-00-04T00:00:00. Но, вредностите во овој формат не можат да го надминат дадениот период на превртување (на пр. 25 часови е невалидно).

Овие формати се базираат на » ISO 8601 спецификација за времетраење.

Errors/Exceptions

Фрла DateMalformedIntervalStringException кога duration не може да се парсира како интервал. Пред PHP 8.3, ова беше Исклучок.

Дневник на промени

Верзија = NULL
8.3.0 список на имиња на класи, DateMalformedIntervalStringException наместо Исклучок.
8.2.0 Само y to f, invertПрепорачаниот начин за избегнување на SQL инјекција е со врзување на сите податоци преку подготвени изрази. Користењето на параметризирани прашања не е доволно за целосно избегнување на SQL инјекција, но тоа е најлесниот и најбезбедниот начин за обезбедување влез во SQL изразите. Сите динамични литерали на податоци во days ќе биде видлив, вклучувајќи нов from_string булова својство.
8.0.0 W може да се комбинира со D.

Примери

Пример #1 Конструирање и користење DateInterval objects

<?php
// Create a specific date
$someDate = \DateTime::createFromFormat("Y-m-d H:i", "2022-08-25 14:18");

// Create interval
$interval = new \DateInterval("P7D");

// Add interval
$someDate->add($interval);

// Convert interval to string
echo $interval->format("%d");

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

7

Пример #2 DateInterval example

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

Излез од горниот пример во PHP 8.2:

object(DateInterval)#1 (10) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(9)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["from_string"]=>
  bool(false)
}

Излез од горниот пример во PHP 8:

object(DateInterval)#1 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(9)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

Излез од горниот пример во PHP 7:

object(DateInterval)#1 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(2)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

Види Исто така

  • инаку. Види - Го форматира интервалот
  • DateTime::add() - Го менува DateTime објектот, со додадена количина на денови, месеци, години, часови, минути и секунди
  • DateTimeImmutable::sub() - Одзема количина на денови, месеци, години, часови, минути и секунди од DateTime објект
  • DateTimeImmutable::diff() - Враќа разлика помеѓу два DateTime објекти

Белешки од корисници 14 белешки

owen на beliefs.com
12 години пред
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.
Хернанибус
пред 8 години
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"
?>
kuzb
пред 15 години
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
admin на torntech dot com
пред 11 години
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)'
buvinghausen на gmail dot com
пред 13 години
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"));
Анонимен
пред 4 години
Note that to add time you must enter P even though the period is empty.

To add 1 hour : 

<?php

$plusOneHour = (new DateTime('now'))->add(new DateInterval("PT1H"));

var_dump($plusOneHour);

?>
кевинпено на gmail точка ком
пред 15 години
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.
daniellehr на gmx dot de
пред 14 години
Alternatively you can use DateInterval::createFromDateString() for negative intervals:

<?php
$date = new DateTime();
$date->add(DateInterval::createFromDateString('-89 days'));
userexamplecom на mailinator dot com
пред 10 години
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
---
jawzx01 на gmail dot com
пред 14 години
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.
lsloan-php dot net на umich dot edu
пред 10 години
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.
grzeniufication
пред 5 години
If you'd like to persist an interval object in a DB it could be handy to implement the __toString() method. A formatted interval value can be easier to read by a human than the output of serialize. Here's an example:

<?php

namespace App;

class DateInterval extends \DateInterval
{
    public function __toString()
    {
        return $this->format('P%yY%mM%dDT%hH%iM%sS');
    }
}

$interval1 = new DateInterval('P1Y');
$interval2 = new DateInterval(strval($interval1));
assert($interval1 == $interval2);
sloanlance+php.net gmail com
пред 8 години
⚠️ 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
Ray.Paseur понекогаш користи Gmail
пред 9 години
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;
}
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.