Finding the number of days between two dates

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

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

30条回答
  •  轮回少年
    2020-11-22 00:06

    Here is my improved version which shows 1 Year(s) 2 Month(s) 25 day(s) if the 2nd parameter is passed.

    class App_Sandbox_String_Util {
        /**
         * Usage: App_Sandbox_String_Util::getDateDiff();
         * @param int $your_date timestamp
         * @param bool $hr human readable. e.g. 1 year(s) 2 day(s)
         * @see http://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates
         * @see http://qSandbox.com
         */
        static public function getDateDiff($your_date, $hr = 0) {
            $now = time(); // or your date as well
            $datediff = $now - $your_date;
            $days = floor( $datediff / ( 3600 * 24 ) );
    
            $label = '';
    
            if ($hr) {
                if ($days >= 365) { // over a year
                    $years = floor($days / 365);
                    $label .= $years . ' Year(s)';
                    $days -= 365 * $years;
                }
    
                if ($days) {
                    $months = floor( $days / 30 );
                    $label .= ' ' . $months . ' Month(s)';
                    $days -= 30 * $months;
                }
    
                if ($days) {
                    $label .= ' ' . $days . ' day(s)';
                }
            } else {
                $label = $days;
            }
    
            return $label;
        }
    }
    

提交回复
热议问题