DateTimeInterface::diff

DateTimeImmutable::diff

DateTime::diff

date_diff

ふたつの DateTime オブジェクトの差を返す

説明

オブジェクト指向型

public DateInterval DateTimeInterface::diff(DateTimeInterface $targetObject, bool $absolute = false)
public DateInterval DateTimeImmutable::diff(DateTimeInterface $targetObject, bool $absolute = false)
public DateInterval DateTime::diff(DateTimeInterface $targetObject, bool $absolute = false)

手続き型

DateInterval date_diff(DateTimeInterface $baseObject, DateTimeInterface $targetObject, bool $absolute = false)

ふたつの DateTime オブジェクトの差を返します。

パラメータ

datetime

比較する日付。

absolute

間隔が正の数になるようにするか否か。

戻り値

ふたつの日付の差をあらわす DateInterval オブジェクトを返します。

さらに厳密に言うと、戻り値はもともとのオブジェクト ($this または $originObject) を $targetObject にするために適用すべき経過時間の差分を示しています。 このプロセスは可逆とは限りません。

このメソッドは夏時間の切り替えを認識するため、 24 hours and 30 minutes という時間差を返す可能性があります。 以下で例示するサンプルコードでそれを示します。 完全な時間差を計算したい場合、 $this/$baseObject$targetObject をUTC に変換する必要があります。

例1 DateTimeImmutable::diff の例

オブジェクト指向型

<?php
$origin 
= new DateTimeImmutable('2009-10-11');
$target = new DateTimeImmutable('2009-10-13');
$interval $origin->diff($target);
echo 
$interval->format('%R%a days');
?>

手続き型

<?php
$origin 
date_create('2009-10-11');
$target date_create('2009-10-13');
$interval date_diff($origin$target);
echo 
$interval->format('%R%a days');
?>

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

+2 days

例2 夏時間の切り替え期間中の DateTimeInterface::diff の動き

<?php
$originalTime 
= new DateTimeImmutable("2021-10-30 09:00:00 Europe/London");
$targedTime = new DateTimeImmutable("2021-10-31 08:30:00 Europe/London");
$interval $originalTime->diff($targedTime);
echo 
$interval->format("%H:%I:%S (Full days: %a)"), "\n";
?>

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

24:30:00 (Full days: 0)

例3 DateTimeInterface::diff range

このメソッドが返す値は、 $this から $targetObject までの範囲から取得した正確な時間です。 よって、(うるう年でない場合) 1月1日から12月31日までを比較すると、 365 ではなく、364 が返ってきます。

<?php
$originalTime 
= new DateTimeImmutable("2023-01-01 UTC");
$targedTime = new DateTimeImmutable("2023-12-31 UTC");
$interval $originalTime->diff($targedTime);
echo 
"Full days: "$interval->format("%a"), "\n";
?>

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

Full days: 364

例4 DateTime オブジェクトの比較

注意:

DateTimeImmutableDateTime オブジェクトは、 比較演算子 で比較することもできます。

<?php
$date1 
= new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 $date2);
var_dump($date1 $date2);
?>

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

bool(false)
bool(true)
bool(false)

参考

  • DateInterval::format
  • DateTime::add
  • DateTime::sub