We have had many requests for a function to compare dates in PHP, so I decided to make this PHP DateDiff function available to the public.

Code Function:

<?php function dateDiff($time1, $time2, $attention = 6) {
        // Set your timezone
        date_default_timezone_set("UTC");
        if (!is_int($time1)){$time1=strtotime($time1);}
        if (!is_int($time2)){$time2=strtotime($time2);}
        if ($time1 > $time2){$time0=$time1;$time1=$time2;$time2=$time0;}
        $periods = array('year','month','day','hour','minute','second');
        $y=array();
        foreach($periods as $period){
            $time0=strtotime('+1 '.$period,$time1);
            $x=1;
            $looped=0;
            while($time2>=$time0){
                $x++;
                $time0 = strtotime("+".$x." ".$period, $time1);
                $looped++;
            }
            $time1 = strtotime("+".$looped." ".$period,$time1);
            $diffs[$period]=$looped;
        }
        $count=0;
        $times=array();
        foreach($y as $period=>$value){
            if($count>=$attention){break;}
            if($value>0) {
                if($value!=1){$period.="s";}
                $times[]=$value." ".$period;
                $count++;
            }
        }
        return implode(", ",$times);
    }
?>

Examples of Use:

<?php
    dateDiff("2013-01-20", "20013-01-25");
    dateDiff("2013-01-20 01:00:00", "2013-01-25 12:00:01");
    dateDiff("now", "now +6 months");
?>

One thought on “PHP DateDiff Function

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>