PHP 8.1.28 Released!

DateTime::modify

date_modify

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

DateTime::modify -- date_modifyタイムスタンプを変更する

説明

オブジェクト指向型

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

手続き型

DateTimeImmutable::__construct() 形式で加算あるいは減算することによって DateTime オブジェクトのタイムスタンプを変更します。

パラメータ

object

手続き型のみ: date_create() が返す DateTime オブジェクト。 この関数は、このオブジェクトを変更します。

modifier

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

戻り値

メソッドチェインに使う、変更された DateTime オブジェクトを返します。失敗した場合に false を返します。

エラー / 例外

オブジェクト指向のAPIのみ、 無効な日付/時刻の文字列が渡された場合に DateMalformedStringException がスローされます。

変更履歴

バージョン 説明
8.3.0 無効な文字列が渡された場合、DateTime::modify() については警告を発生させるのではなく DateMalformedStringException がスローされるようになりました。 date_modify() は変更されていません。

例1 DateTime::modify() の例

オブジェクト指向型

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

手続き型

<?php
$date
= date_create('2006-12-12');
date_modify($date, '+1 day');
echo
date_format($date, 'Y-m-d');
?>

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

2006-12-13

例2 月の加減算には注意

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

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

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

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

2001-01-31
2001-03-03

例3 全ての日付と時刻のフォーマットがサポートされています

<?php
$date
= new DateTime('2020-12-31');

$date->modify('July 1st, 2023');
echo
$date->format('Y-m-d H:i') . "\n";

$date->modify('Monday next week');
echo
$date->format('Y-m-d H:i') . "\n";

$date->modify('17:30');
echo
$date->format('Y-m-d H:i') . "\n";
?>

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

2023-07-01 00:00
2023-07-03 00:00
2023-07-03 17:30

参考

add a note

User Contributed Notes 1 note

up
0
php_net at striderweb dot com
1 hour ago
You have to be a bit careful with variables here. If for example you want to add a variable amount of minutes you might use `->modify("+$min"). This will not work out if `$min` is a negative number, because modify will see the "+" and ignore the "-". If `$min` equals -10, modify in this example will add ten minutes, not subtract!

What is happening is if the modify string has two operations, the first will be obeyed and later ones will be ignored.

So "+-10 minutes" will add ten minutes, even though you might expect it to add the negative number. Similarly "--10 minutes" will subtract ten minutes, despite the apparent logic of subtracting a negative number.
To Top