如何使用PHP中的两个日期计算夜晚的数量

时间:2017-09-21 06:20:43

标签: php

这是我的代码。

$checkinDate = $_POST['checkinDate'];
$checkoutDate = $_POST['checkoutDate'];
$no_nights = date_diff($checkinDate, $checkoutDate);

我的代码错误:

Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given in C:\xampp\htdocs\lgh-hms\admin\conformation.php on line 19

1 个答案:

答案 0 :(得分:1)

date_diff需要日期,而不是字符串......

程序风格:

$checkinDate = date_create($_POST['checkinDate']);
$checkoutDate = date_create($_POST['checkoutDate']);
$interval = date_diff($checkinDate,$checkoutDate);
$no_nights = $interval->format('%a');

使用对象:

$checkinDate = new DateTime($_POST['checkinDate']);
$checkoutDate = new DateTime($_POST['checkoutDate']);
$interval = $checkinDate->diff($checkoutDate);
$no_nights = $interval->format('%a');

我希望它有所帮助