I think it is easiest if you would just use the sub method on the DateTime class.
<?php
$date = new DateTime();
$date->sub(new DateInterval("P89D"));
DateInterval::__construct
(PHP 5 >= 5.3.0)
DateInterval::__construct — 新しい DateInterval オブジェクトを作成する
説明
$interval_spec
)新しい DateInterval オブジェクトを作成します。
パラメータ
-
interval_spec -
間隔。
最初は P から始まります。これは "period" を表します。 間隔の単位は、整数値の後に間隔指示子をつけて表します。 時間の要素を含む場合は、時間部分の前に文字 T を入れます。
interval_specの間隔指示子間隔指示子 説明 Y 年 M 月 D 日 W 週。日付に変換されるので D と組み合わせて使うことはできません。 H 時間 M 分 S 秒 いくつか簡単な例を示しましょう。 P2D は 2 日、 PT2S は 2 秒、そして P6YT5M は 6 年と 5 分を表します。
注意:
複数の単位を指定するときは、 大きな単位を左、小さな単位を右の順に書かなければなりません。 つまり年は月より先、月は日より先、日は分より先などとなります。 1 年と 4 日を表すのは P1Y4D であり、P4D1Y ではありません。
日付と時刻で間隔を指定することもできます。 1 年と 4 日をこの方式で表すと P0001-00-04T00:00:00 のようになります。 しかし、この方式では繰り返し単位以上の値を指定することはできません (たとえば 25 時間などとは指定できません)。
これらのフォーマットは » ISO 8601 duration specification に基づくものです。
例
<?php
$interval = new DateInterval('P2Y4DT6H8M');
var_dump($interval);
?>
上の例の出力は以下となります。
object(DateInterval)#1 (8) {
["y"]=>
int(2)
["m"]=>
int(0)
["d"]=>
int(4)
["h"]=>
int(6)
["i"]=>
int(8)
["s"]=>
int(0)
["invert"]=>
int(0)
["days"]=>
bool(false)
}
参考
- DateInterval::format() - 間隔をフォーマットする
- DateTime::add() - 年月日時分秒の値を DateTime オブジェクトに加える
- DateTime::sub() - 年月日時分秒の値を DateTime オブジェクトから引く
- DateTime::diff() - ふたつの DateTime オブジェクトの差を返す
Alternatively you can use DateInterval::createFromDateString() for negative intervals:
<?php
$date = new DateTime();
$date->add(DateInterval::createFromDateString('-89 days'));
As previously mentioned, to do a negative DateInterval object, you'd code:
<?php
$date1 = new DateTime();
$eightynine_days_ago = new DateInterval( "P89D" );
$eightynine_days_ago->invert = 1; //Make it negative.
$date1->add( $eightynine_days_ago );
?>
and then $date1 is now 89 days in the past.
Note that, while a DateInterval object has an $invert property, you cannot supply a negative directly to the constructor similar to specifying a negative in XSD ("-P1Y"). You will get an exception through if you do this.
Instead you need to construct using a positive interval ("P1Y") and the specify the $invert property === 1.
It should be noted that this class will not calculate days/hours/minutes/seconds etc given a value in a single denomination of time. For example:
<?php
$di = new DateInterval('PT3600S');
echo $di->format('%H:%i:%s');
?>
will yield 0:0:3600 instead of the expected 1:0:0
