note 78981 added to ref.datetime
| From: | stoicnluv at gmail dot com | Date: | Mon, 05 Nov 2007 23:14:33 +0000 |
| Subject: | note 78981 added to ref.datetime | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132021@lists.php.net to get a copy of this message | ||
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 -- https://master.php.net/note/delete/78981/integrated
Del: useless -- https://master.php.net/note/delete/78981/useless
Del: bad code -- https://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 -- https://master.php.net/note/delete/78981/in+docs
Del: other reasons-- https://master.php.net/note/delete/78981
Reject -- https://master.php.net/note/reject/78981
Search -- https://master.php.net/manage/user-notes.php