php计算两个日期相差天数的方法1:
use Carbon\Carbon;
...
$date1 = Carbon::parse('2023-03-01');
$date2 = Carbon::parse('2025-05-30');
$date1->diffInDays($date2);//相差天数的绝对值(正数)
$date1->diffInDays($date2,false);//正数或负数
php计算两个日期相差天数的方法2:
<?php
/**
* 求两个日期之间相差的天数
* @param string $day1
* @param string $day2
* @return float|int
*/
function diffBetweenTwoDays (string $day1, string $day2)
{
$second1 = strtotime($day1);
$second2 = strtotime($day2);
if ($second1 < $second2) {
$tmp = $second2;
$second2 = $second1;
$second1 = $tmp;
}
return ($second1 - $second2) / 86400;
}
$day1 = "2023-01-01";
$day2 = "2023-08-31";
$diff = diffBetweenTwoDays($day1, $day2);
echo $diff.PHP_EOL;