downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

DateTime::__construct> <DateTime
[edit] Last updated: Fri, 25 May 2012

view this page in

DateTime::add

date_add

(PHP 5 >= 5.3.0)

DateTime::add -- date_add 年月日時分秒の値を DateTime オブジェクトに加える

説明

オブジェクト指向型

public DateTime DateTime::add ( DateInterval $interval )

手続き型

DateTime date_add ( DateTime $object , DateInterval $interval )

指定した DateInterval オブジェクトを、 指定した 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($datedate_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() を使うことができます。

参考



add a note add a note User Contributed Notes DateTime::add
Anonymous 01-Feb-2011 02:16
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.)
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

 
show source | credits | stats | sitemap | contact | advertising | mirror sites