如何使用PHP找到两个日期之间的天数?


当前回答

$start = '2013-09-08';
$end = '2013-09-15';
$diff = (strtotime($end)- strtotime($start))/24/3600; 
echo $diff;

其他回答

这段代码为我工作,并用PHP 8版本测试:

function numberOfDays($startDate, $endDate) 
{
    //1) converting dates to timestamps
     $startSeconds = strtotime($startDate);
     $endSeconds = strtotime($endDate);
   
    //2) Calculating the difference in timestamps
    $diffSeconds = $startSeconds  - $endSeconds;
     
    
    //3) converting timestamps to days
    $days=round($diffSeconds / 86400);
    
      /*  note :
          1 day = 24 hours 
          24 * 60 * 60 = 86400 seconds
      */
   
    //4) printing the number of days
    printf("Difference between two dates: ". abs($days) . " Days ");
    
    return abs($days);
}
$early_start_date = date2sql($_POST['early_leave_date']);


$date = new DateTime($early_start_date);
$date->modify('+1 day');


$date_a = new DateTime($early_start_date . ' ' . $_POST['start_hr'] . ':' . $_POST['start_mm']);
$date_b = new DateTime($date->format('Y-m-d') . ' ' . $_POST['end_hr'] . ':' . $_POST['end_mm']);

$interval = date_diff($date_a, $date_b);


$time = $interval->format('%h:%i');
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60;
//        display_error($seconds);

$second3 = $employee_information['shift'] * 60 * 60;

if ($second3 < $seconds)
    display_error(_('Leave time can not be greater than shift time.Please try again........'));
    set_focus('start_hr');
    set_focus('end_hr');
    return FALSE;
}

从PHP 5.3及以上版本开始,添加了新的日期/时间函数来获得不同:

$datetime1 = new DateTime("2010-06-20");

$datetime2 = new DateTime("2011-06-22");

$difference = $datetime1->diff($datetime2);

echo 'Difference: '.$difference->y.' years, ' 
                   .$difference->m.' months, ' 
                   .$difference->d.' days';

print_r($difference);

结果如下:

Difference: 1 years, 0 months, 2 days

DateInterval Object
(
    [y] => 1
    [m] => 0
    [d] => 2
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 367
)

希望能有所帮助!

出于类似的目的,我在我的作曲项目中使用Carbon。

就像这样简单:

$dt = Carbon::parse('2010-01-01');
echo $dt->diffInDays(Carbon::now());

你可以试试下面的代码:

$dt1 = strtotime("2019-12-12"); //Enter your first date
$dt2 = strtotime("12-12-2020"); //Enter your second date
echo abs(($dt1 - $dt2) / (60 * 60 * 24));