Tuesday, August 28, 2012

Calculate date and time diff in PHP

public function  calculateDateDiff($date1,$date2)
    {
            $string_diff = array();
            $diff = abs(strtotime($date2) - strtotime($date1));
            $years   = floor($diff / (365*60*60*24));
            $months  = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
            $days    = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
            $hours   = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
            $minutes  = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
            $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minutes*60));
            if($years >=1 ){
                $string_diff[]= $years.' Year'.(($years>1)?'s':'');
            }
            if($months >=1 ){
                $string_diff[]= $months.' Month'.(($months>1)?'s':'');
            }
            if($days >=1 ){
                $string_diff[]= $days.' Day'.(($days>1)?'s':'');
            }
            if($hours >=1 ){
                $string_diff[]= $hours.' Hour'.(($hours>1)?'s':'');
            }
            if($minutes >=1 ){
                $string_diff[]= $minutes.' Minute'.(($minutes>1)?'s':'');
            }
            return implode (',', $string_diff);
    }

No comments:

Post a Comment