dateinterval php
<?php
$d1=new DateTime("2012-07-08 11:14:15.638276");
$d2=new DateTime("2012-07-08 11:14:15.889342");
$diff=$d2->diff($d1);
print_r( $diff ) ;
?>
// Note: it now DOES return microsecond differences, in the key 'f':
<?php
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 0
[i] => 0
[s] => 0
[f] => 0.251066
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
?>
<?php
$one_year = new DateInterval('P1Y');
$one_year_ago = new DateTime();
$one_year_ago->sub($one_year);
?>
Please note that the hour field can be negative, especially in the context of switching to/from Daylight savings.
Example:
<?php
$tz = new DateTimeZone("America/New_York");
$date_1 = new DateTime("2019-10-30 15:00:00",$tz);
$date_2 = new DateTime("2019-11-21 14:30:20",$tz);
echo $date_2->diff($date_1)->format("%a:%h:%i:%s");
// returns 21:-1:30:20
?>