Php datetime to dateinterval

Php datetime to dateinterval

Fullstack JavaScript разработчик

Работа с DateInterval в PHP

Подробное рассмотрение встроенного PHP класса DateInterval

DateInterval — представляет собой некую продолжительность времени, которую мы можем использовать при сдвигах даты.

В обычном разговоре, вы ведь вряд-ли скажете «я буду у тебя 2 января 2015 года в 7:38«?

Естественно, вместо этого намного уместнее будет сказать – «я буду у тебя через 10 минут».

Но как объяснить интерпретатору PHP, что значит эта заветная фраза «через 10 минут«?

Именно для таких ситуаций и используется DateInterval.

Рассмотрим элементарный пример использования:

add($dateInterval)->format("d"); echo "послезавтра будет " . $tomorrow . " число" 

Конструктор DateInterval и Iso 8601

Вся магия заключается в строке переданной в конструктор — ‘P1D’. Что это за P1D? Согласно стандарту ISO 8601-2004 (или ГОСТ ИСО 8601-2001), P и D являются знаками, использующимся в качестве указателей (designator) (п. 3.4.3 и 4.4 версий стандартов соответственно). Для использования DateInterval понадобится запомнить всего лишь несколько указателей:

Указатель Расшифровка Описание
P Period Начало периода времени
Y Year Год
M Month Месяц
D Day День
T Time Начало представления объекта времени
H Hour Часы
M Minute Минуты
S Secunde Секунды

Единственный обязательный указатель — P, все остальные опциональны.

Посмотрим на пару примеров:

Любой другой период можно составить по аналогии P

Анатомия класса DateInterval

DateInterval содержит в себе только конструктор и два открытых метода.

  1. staticcreateFromDateString — создает объект DateInterval из строки относительного формата времени
  2. format — форматирует интервал для вывода

Также у класса есть открытые члены:

Используя их можно динамически управлять периодом.

Давайте представим, что мы реализуем систему подачи заявок на предзаказ, причем анонимные посетители могут оформить предзаказ только за неделю до появления товара, а зарегистрированные, за три недели.

Предположим что наша система разрабатывается на Yii, в коде это можно было бы выразить так:

user->isGuest) $di->d += 14; $date_to = (new DateTime)->add($di); // получаем все товары с датой выхода между сегодня и $criteria->addBetweenCondition('release_date', $date_from, $date_to); // . code 

Таким образом, если выполняется условие !Yii::app()->user->isGuest, т.е. пользователь зарегистрирован, интервал будет увеличен на 14 дней, соответственно зарегистрированный пользователь увидит товары с предзаказом за 21 день перед появлением.

Источник

The DateInterval class

A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTimeImmutable ‘s and DateTime ‘s constructors support.

More specifically, the information in an object of the DateInterval class is an instruction to get from one date/time to another date/time. This process is not always reversible.

A common way to create a DateInterval object is by calculating the difference between two date/time objects through DateTimeInterface::diff() .

Since there is no well defined way to compare date intervals, DateInterval instances are incomparable.

Class synopsis

Properties

The available properties listed below depend on PHP version, and should be considered as readonly.

Number of microseconds, as a fraction of a second.

Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format() .

If the DateInterval object was created by DateTimeImmutable::diff() or DateTime::diff() , then this is the total number of full days between the start and end dates. Otherwise, days will be false .

If the DateInterval object was created by DateInterval::createFromDateString() , then this property’s value will be true , and the date_string property will be populated. Otherwise, the value will be false , and the y to f , invert , and days properties will be populated.

Changelog

Version Description
8.2.0 The from_string and date_string properties were added for DateInterval instances that were created using the DateInterval::createFromDateString() method.
8.2.0 Only the y to f , invert , and days will be visible.
7.4.0 DateInterval instances are incomparable now; previously, all DateInterval instances were considered equal.
7.1.0 The f property was added.

Table of Contents

  • DateInterval::__construct — Creates a new DateInterval object
  • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
  • DateInterval::format — Formats the interval

Источник

DateInterval::__construct

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 .

duration Period Designators

Period Designator Description
Y years
M months
D days
W weeks. Converted into days. Prior to PHP 8.0.0, can not be combined with D .
H hours
M minutes
S seconds

Here are some simple examples. Two days is P2D . Two seconds is PT2S . Six years and five minutes is P6YT5M .

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

The specification can also be represented as a date time. A sample of one year and four days would be P0001-00-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).

Errors/Exceptions

Throws an Exception when the duration cannot be parsed as an interval.

Changelog

Version Description
8.2.0 Only the y to f , invert , and days will be visible, including a new from_string boolean property.
8.0.0 W can be combined with D .

Examples

Example #1 Constructing and using DateInterval objects

// 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» );

The above example will output:

Example #2 DateInterval example

$interval = new DateInterval ( ‘P1W2D’ );
var_dump ( $interval );

Output of the above example in 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) >

Output of the above example in 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) >

Output of the above example in 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) >

See Also

  • DateInterval::format() — Formats the interval
  • DateTime::add() — Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
  • DateTime::sub() — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() — Returns the difference between two DateTime objects

User Contributed Notes 15 notes

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

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

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»
?>

I think it is easiest if you would just use the sub method on the DateTime class.

$date = new DateTime ();
$date -> sub (new DateInterval ( «P89D» ));

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:

$di = new DateInterval ( ‘PT3600S’ );
echo $di -> format ( ‘%H:%i:%s’ );

?>

will yield 0:0:3600 instead of the expected 1:0:0

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.

/* 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)’

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.

Alternatively you can use DateInterval::createFromDateString() for negative intervals:

$date = new DateTime ();
$date -> add ( DateInterval :: createFromDateString ( ‘-89 days’ ));

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

As previously mentioned, to do a negative DateInterval object, you’d code:

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

⚠️ 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:

// ‘P0.5Y’ is valid according to ISO 8601
$interval = new DateInterval ( ‘P0.5Y’ ); // Throws exception
?>

// ‘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

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.

Note that to add time you must enter P even though the period is empty.

$plusOneHour = (new DateTime ( ‘now’ ))-> add (new DateInterval ( «PT1H» ));

Источник

Читайте также:  Typescript one of interface
Оцените статью