CakeFest 2024: The Official CakePHP Conference

DateTimeImmutable::modify

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

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

説明

public DateTimeImmutable::modify(string $modifier): DateTimeImmutable|false

タイムスタンプを変更した新しい 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

参考

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top