Page 1 of 1

[PHP]counting how many yrs, mths and d's go since any date

Posted: Mon Apr 26, 2010 11:54 am
by kecajs

Code: Select all

counting how many years, months and days go since any date past to current date, eg. 15-05-2007 (historical date) - 26-04-2010 (current date) = 2 years, 11 months, 19 days.
I've tried something like this:
[syntax=php]
<?php
$d1 = strtotime('2007-05-15');
$d2 = time();
 
$y1 = date('Y', $d1);
$y2 = date('Y', $d2);
$m1 = date('n', $d1);
$m2 = date('n', $d2);
$da1 = date('d', $d1);
$da2 = date('d', $d2);
 
$year_diff = $y2 - $y1;
$month_diff = $m2 - $m1;
$days_diff = $d2 - $d1;
 
echo $year_diff. " years, " .$month_diff. " months, " .$days_diff. " days";
 ?>
[/syntax]
but this script doesn't working exactly what i need: it deduct years, months and days separatly - 2010-2007=3 years,  04-05= -1 months, 26-15= 93120711 days.

Please, help me to solve this problem.

Best regards,
Jack

Re: [PHP]counting how many yrs, mths and d's go since any da

Posted: Mon Apr 26, 2010 2:02 pm
by Jonah Bron
A quick search returned this

http://www.gidnetwork.com/b-16.html

query "php date difference"

Re: [PHP]counting how many yrs, mths and d's go since any da

Posted: Mon Apr 26, 2010 3:03 pm
by AbraCadaver
Here's one from php.net that does months and years and take DST and leap years into account:

Code: Select all

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)
    );
}