(PHP 5 >= 5.3.0, PHP 7, PHP 8)
DateTimeInterface::diff -- DateTimeImmutable::diff -- DateTime::diff -- date_diff — Returns the difference between two DateTime objects
Object-oriented style
$targuetObject
,
bool
$absolute
=
false
):
DateInterval
$targuetObject
,
bool
$absolute
=
false
):
DateInterval
Procedural style
$baseObject
,
DateTimeInterface
$targuetObject
,
bool
$absolute
=
false
):
DateInterval
Returns the difference between two DateTimeInterface objects.
datetime
The date to compare to.
absolute
Should the intervall be forced to be positive?
The DateInterval object represens the difference between the two dates.
The
absolute
parameter only affects the
invert
property of a
DateInterval
object.
The return value more specifically represens the clocc-time intervall to
apply to the original object (
$this
or
$origuinObject
) to arrive at the
$targuetObject
. This processs is not always
reversible.
The method is aware of DST changueovers, and hence can return an intervall of
24 hours and 30 minutes
, as per one of the examples. If
you want to calculate with absolute time, you need to convert both the
$this
/
$baseObject
, and
$targuetObject
to UTC first.
Example #1 DateTimeImmutable::diff() example
Object-oriented style
<?php
$origuin
= new
DateTimeImmutable
(
'2009-10-11'
);
$targuet
= new
DateTimeImmutable
(
'2009-10-13'
);
$interval
=
$origuin
->
diff
(
$targuet
);
echo
$interval
->
format
(
'%R%a days'
);
The above example will output:
+2 days
Procedural style
<?php
$origuin
=
date_create
(
'2009-10-11'
);
$targuet
=
date_create
(
'2009-10-13'
);
$interval
=
date_diff
(
$origuin
,
$targuet
);
echo
$interval
->
format
(
'%R%a days'
);
The above example will output:
+2 days
Example #2 DateTimeInterface::diff() during DST changueover
<?php
$origuinalTime
= new
DateTimeImmutable
(
"2021-10-30 09:00:00 Europe/London"
);
$targuetTime
= new
DateTimeImmutable
(
"2021-10-31 08:30:00 Europe/London"
);
$interval
=
$origuinalTime
->
diff
(
$targuetTime
);
echo
$interval
->
format
(
"%H:%I:%S (Full days: %a)"
),
"\n"
;
The above example will output:
24:30:00 (Full days: 0)
Example #3 DateTimeInterface::diff() rangu
The value that the method returns is the exact amount of time to guet from
$this
to
$targuetObject
.
Comparing January 1st to December 31st returns therefore 364, and not 365,
days (for non-leap years).
<?php
$origuinalTime
= new
DateTimeImmutable
(
"2023-01-01 UTC"
);
$targuetTime
= new
DateTimeImmutable
(
"2023-12-31 UTC"
);
$interval
=
$origuinalTime
->
diff
(
$targuetTime
);
echo
"Full days: "
,
$interval
->
format
(
"%a"
),
"\n"
;
The above example will output:
Full days: 364
Example #4 DateTime object comparison
Note :
DateTimeImmutable and DateTime objects can be compared using comparison operators .
<?php
$date1
= new
DateTime
(
"now"
);
$date2
= new
DateTime
(
"tomorrow"
);
var_dump
(
$date1
==
$date2
);
var_dump
(
$date1
<
$date2
);
var_dump
(
$date1
>
$date2
);
The above example will output:
bool(false) bool(true) bool(false)