A better and accurate function to calculate the difference
between 2 dates. Takes leap years and DST into
consideration. Accepts string date or timestamp as
arguments.
<?php
function date_diff($d1, $d2){
$d1 = (is_string($d1) ? strtotime($d1) : $d1);
$d2 = (is_string($d2) ? strtotime($d2) : $d2);
$diff_secs = abs($d1 - $d2);
$base_year = min(date("Y", $d1),
date("Y", $d2));
$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
return array(
"years" => date("Y", $diff) -
$base_year,
"months_total" => (date("Y", $diff)
- $base_year) * 12 + date("n", $diff) - 1,
"months" => date("n", $diff) - 1,
"days_total" => floor($diff_secs / (3600 *
24)),
"days" => date("j", $diff) - 1,
"hours_total" => floor($diff_secs / 3600),
"hours" => date("G", $diff),
"minutes_total" => floor($diff_secs / 60),
"minutes" => (int) date("i",
$diff),
"seconds_total" => $diff_secs,
"seconds" => (int) date("s",
$diff)
);
}
$a = date_diff("2006-11-01",
"2007-11-01");
echo "<pre>";
print_r($a);
echo "</pre>";
?>
This example will output (if your timezone uses US DST):
Array
(
[years] => 0
[months_total] => 11
[months] => 11
[days_total] => 364
[days] => 30
[hours_total] => 8759
[hours] => 23
[minutes_total] => 525540
[minutes] => 0
[seconds_total] => 31532400
[seconds] => 0
)
As you can see, the result is not exactly 1 year (less 1
hour) since Nov 1, 2006 is not DST while Nov 1, 2007 is
DST.
----
Server IP: 69.147.83.197
Probable Submitter: 125.5.144.90
----
Manual Page -- http://
www.php.net/manual/en/ref.datetime.php
Edit -- https://master
.php.net/note/edit/78981
Del: integrated -- h
ttps://master.php.net/note/delete/78981/integrated
Del: useless -- http
s://master.php.net/note/delete/78981/useless
Del: bad code -- htt
ps://master.php.net/note/delete/78981/bad+code
Del: spam -- https:/
/master.php.net/note/delete/78981/spam
Del: non-english --
https://master.php.net/note/delete/78981/non-english
Del: in docs -- http
s://master.php.net/note/delete/78981/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78981
Reject -- https://mast
er.php.net/note/reject/78981
Search -- https://
master.php.net/manage/user-notes.php
--
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php
|