1
2<?php
3$d1=new DateTime("2012-07-08 11:14:15.638276");
4$d2=new DateTime("2012-07-08 11:14:15.889342");
5$diff=$d2->diff($d1);
6print_r( $diff ) ;
7?>
8
9// Note: it now DOES return microsecond differences, in the key 'f':
10
11<?php
12DateInterval Object
13(
14 [y] => 0
15 [m] => 0
16 [d] => 0
17 [h] => 0
18 [i] => 0
19 [s] => 0
20 [f] => 0.251066
21 [weekday] => 0
22 [weekday_behavior] => 0
23 [first_last_day_of] => 0
24 [invert] => 1
25 [days] => 0
26 [special_type] => 0
27 [special_amount] => 0
28 [have_weekday_relative] => 0
29 [have_special_relative] => 0
30)
31?>
32
33<?php
34 $one_year = new DateInterval('P1Y');
35 $one_year_ago = new DateTime();
36 $one_year_ago->sub($one_year);
37?>
38
39Please note that the hour field can be negative, especially in the context of switching to/from Daylight savings.
40
41Example:
42<?php
43
44 $tz = new DateTimeZone("America/New_York");
45 $date_1 = new DateTime("2019-10-30 15:00:00",$tz);
46 $date_2 = new DateTime("2019-11-21 14:30:20",$tz);
47 echo $date_2->diff($date_1)->format("%a:%h:%i:%s");
48 // returns 21:-1:30:20
49?>