DateTimeImmutable::modify

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

説明

public DateTimeImmutablefalse DateTimeImmutable::modify(string $modifier)

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

パラメータ

modifier

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

戻り値

新しく作った DateTimeImmutable オブジェクトを返します。 失敗した場合に false を返します

エラー / 例外

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

変更履歴

バージョン 説明
8.3.0 不正な文字列が渡された場合に、警告を発生させるのではなく、 DateMalformedStringException がスローされるようになりました。

例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