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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kecajs
Forum Newbie
Posts: 1
Joined: Mon Apr 26, 2010 11:39 am

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

Post 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
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

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

Post by Jonah Bron »

A quick search returned this

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

query "php date difference"
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

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

Post 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)
    );
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply