Finding the number of days between two dates

后端 未结 30 3034
心在旅途
心在旅途 2020-11-21 23:47

How to find number of days between two dates using PHP?

30条回答
  •  没有蜡笔的小新
    2020-11-22 00:13

    Looking all answers I compose universal function what working on all PHP versions.

    if(!function_exists('date_between')) :
        function date_between($date_start, $date_end)
        {
            if(!$date_start || !$date_end) return 0;
    
            if( class_exists('DateTime') )
            {
                $date_start = new DateTime( $date_start );
                $date_end   = new DateTime( $date_end );
                return $date_end->diff($date_start)->format('%a');
            }
            else
            {           
                return abs( round( ( strtotime($date_start) - strtotime($date_end) ) / 86400 ) );
            }
        }
    endif;
    

    In the general, I use 'DateTime' to find days between 2 dates. But if in the some reason, some server setup not have 'DateTime' enabled, it will use simple (but not safe) calculation with 'strtotime()'.

提交回复
热议问题