Note that the add() and sub() methods will modify the value of the object you're calling the method on! This is very untypical for a method that returns a value of its own type. You could misunderstand it that the method would return a new instance with the modified value, but in fact it modifies itself! This is undocumented here. (Only a side note on procedural style mentions it, but it obviously does not apply to object oriented style.)
DateTime::add
date_add
(PHP 5 >= 5.3.0)
DateTime::add -- date_add — 年月日時分秒の値を DateTime オブジェクトに加える
パラメータ
-
object -
手続き型のみ: date_create() が返す DateTime オブジェクト。 この関数は、このオブジェクトを変更します。
-
interval -
DateInterval オブジェクト。
返り値
メソッドチェインに使う DateTime オブジェクトを返します。失敗した場合に FALSE を返します。
例
例1 DateTime::add() の例
オブジェクト指向型
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>
手続き型
<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>
上の例の出力は以下となります。
2000-01-11
例2 DateTime::add() の別の例
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
上の例の出力は以下となります。
2000-01-01 10:00:30 2007-06-05 04:03:02
例3 月を加算するときの注意点
<?php
$date = new DateTime('2000-12-31');
$interval = new DateInterval('P1M');
$date->add($interval);
echo $date->format('Y-m-d') . "\n";
$date->add($interval);
echo $date->format('Y-m-d') . "\n";
?>
上の例の出力は以下となります。
2001-01-31 2001-03-03
注意
PHP 5.2 では、かわりに DateTime::modify() を使うことができます。
参考
- DateTime::sub() - 年月日時分秒の値を DateTime オブジェクトから引く
- DateTime::diff() - ふたつの DateTime オブジェクトの差を返す
- DateTime::modify() - タイムスタンプを変更する
Anonymous
01-Feb-2011 02:16
fortruth at mabang dot net
23-Aug-2010 11:00
adding 15 min to a datetime
<?php
$initDate = new DateTime("2010/08/24");
$initDate->add(new DateInterval("PT15M"));
echo $initDate->format("Y/m/d m:i:s");//result: 2010/08/24 08:15:00
?>
period:
P1Y2M3DT1H2M3S
period time:
PT1H2M3S
