« DateTimeImmutable::getLastErrors
DateTimeImmutable::__set_state »

DateTimeImmutable::modify

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

DateTimeImmutable::modify — タイムスタンプを変更した新しいオブジェクトを作る

説明

#[\NoDiscard(message: "as DateTimeImmutable::modify() does not modify the object itself")]
public function DateTimeImmutable::modify(string $modifier): DateTimeImmutable

タイムスタンプを変更した新しい DateTimeImmutable オブジェクトを作ります。 元のオブジェクトは変更されません。

パラメータ

modifier

日付/時刻 文字列。有効な書式については 日付と時刻の書式 で説明しています。

戻り値

成功時に DateTimeImmutable を返します。 手続き型 の場合は、失敗したときに false を返します。

エラー / 例外

無効な日付/時刻の文字列が渡された場合、 DateMalformedStringException がスローされます。 PHP 8.3.0 より前のバージョンでは、警告が発生していました。

変更履歴

バージョン 説明
8.4.0 仮の戻り値の型が、DateTimeImmutable になりました。 これより前のバージョンでは、 DateTimeImmutable|false でした。
8.3.0 無効な文字列が渡された場合、 DateTimeImmutable::modify() は DateMalformedStringException をスローするようになりました。 これより前のバージョンでは、 警告が発生して false を返していました。

例

例1 DateTimeImmutable::modify() の例

オブジェクト指向型

<?php
$date = new DateTimeImmutable('2006-12-12');
$newDate = $date->modify('+1 day');
echo $newDate->format('Y-m-d');

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

2006-12-13

例2 月の加減算には注意

<?php
$date = new DateTimeImmutable('2000-12-31');

$newDate1 = $date->modify('+1 month');
echo $newDate1->format('Y-m-d') . "\n";

$newDate2 = $newDate1->modify('+1 month');
echo $newDate2->format('Y-m-d') . "\n";

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

2001-01-31
2001-03-03

参考

関連キーワード:
DateTimeImmutable   modify   newDate   日付   タイムスタンプ   時刻   date   format   modifier   書式   無効   DateMalformedStringException   month   年月日   分秒   getLastErrors   state   NoDiscard   message   itself   成功   手続き   履歴   スロー   オブジェクト指向
関連する関数・ページ:
datetimeimmutable.add   datetime.modify   datetimeimmutable.sub   datetimeimmutable.settimestamp   datetimeimmutable.setdate   datetimeimmutable.setisodate