DateTimeImmutable::modify

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

説明

#[\NoDiscard] public DateTimeImmutable DateTimeImmutable::modify(string $modifier)

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

パラメータ

modifier

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

戻り値

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

エラー / 例外

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

変更履歴

バージョン 説明
8.3.0 無効な文字列が渡された場合、 DateTimeImmutable::modifyDateMalformedStringException をスローするようになりました。 これより前のバージョンでは、 警告が発生して 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::add
  • DateTimeImmutable::sub
  • DateTimeImmutable::setDate
  • DateTimeImmutable::setISODate
  • DateTimeImmutable::setTime
  • DateTimeImmutable::setTimestamp