DateInterval::createFromDateString

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

DateInterval::createFromDateString相対指定文字列から DateInterval を作成する

説明

オブジェクト指向型

publicstaticDateInterval::createFromDateString(string$datetime): DateInterval|false

手続き型

DateTimeImmutable のコンストラクタで使われている日付パーサを用いて、パースされた相対指定文字列から DateInterval を作成します。

パラメータ

datetime

相対部分を含む日付。 特に、strtotime()DateTimeImmutableDateTime が使うパーサーがサポートする 相対書式 を使って DateInterval を作ることができます。

P7D のような ISO-8601 フォーマットの文字列を使うには、 DateInterval のコンストラクタを使わなければいけません。

戻り値

新しい DateInterval のインスタンスを返します。 失敗した場合に false を返します

変更履歴

バージョン説明
8.2.0 このメソッドを使って DateInterval を作った場合、 アクセス可能なプロパティは from_stringdate_string だけになりました。

例1 日付の間隔のパース

<?php
// セットになっているふたつは、それぞれ同じ間隔を表します。
$i = new DateInterval('P1D');
$i = DateInterval::createFromDateString('1 day');

$i = new DateInterval('P2W');
$i = DateInterval::createFromDateString('2 weeks');

$i = new DateInterval('P3M');
$i = DateInterval::createFromDateString('3 months');

$i = new DateInterval('P4Y');
$i = DateInterval::createFromDateString('4 years');

$i = new DateInterval('P1Y1D');
$i = DateInterval::createFromDateString('1 year + 1 day');

$i = new DateInterval('P1DT12H');
$i = DateInterval::createFromDateString('1 day + 12 hours');

$i = new DateInterval('PT3600S');
$i = DateInterval::createFromDateString('3600 seconds');
?>

例2 パース処理の組み合わせと、負の間隔

<?php
$i
= DateInterval::createFromDateString('62 weeks + 1 day + 2 weeks + 2 hours + 70 minutes');
echo
$i->format('%d %h %i'), "\n";

$i = DateInterval::createFromDateString('1 year - 10 days');
echo
$i->format('%y %d'), "\n";
?>

上の例の出力は以下となります。


449 2 70
1 -10

例3 特別な相対書式の間隔をパースする

<?php
$i
= DateInterval::createFromDateString('last day of next month');
var_dump($i);

$i = DateInterval::createFromDateString('last weekday');
var_dump($i);

上の例の PHP 8.2 での出力は、このようになります。:

object(DateInterval)#1 (2) { ["from_string"]=> bool(true) ["date_string"]=> string(22) "last day of next month" } object(DateInterval)#2 (2) { ["from_string"]=> bool(true) ["date_string"]=> string(12) "last weekday" }

上の例の PHP 8 での出力は、たとえば以下のようになります。:

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