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
        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');
        foreach($periods as $period){
            $time0=strtotime('+1 '.$period,$time1);
                $time0 = strtotime("+".$x." ".$period, $time1);
            $time1 = strtotime("+".$looped." ".$period,$time1);
        foreach($y as $period=>$value){
            if($value>0) {
                $times[]=$value." ".$period;
        return implode(", ",$times);

Examples of Use:

    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>