我如何将 date_diff 函数与字符串值一起使用
How can i use date_diff function with string values
我有 2 个字符串值,例如“24/10/2015”和“23/10/2015”,它们是动态值。我需要这两个值之间的夜间计数,所以我尝试使用 date_diff 但我无法管理它。我尝试过 strtotime、date_create_from_format 等,但没有用。有什么建议吗?
示例代码:
$checkout = $_COOKIE['cout'];
$checkin = $_COOKIE['cin'];
$nights = date_diff(strtotime($checkout),strtotime($checkin));
这应该适合你:
只需创建一个 DateTime
object with DateTime::createFromFormat()
and then you can get the difference with diff()
,像这样:
<?php
$dateOne = "24/10/2015";
$dateTwo = "23/10/2015";
$dateOne = DateTime::createFromFormat("d/m/Y", $dateOne);
$dateTwo = DateTime::createFromFormat("d/m/Y", $dateTwo);
$interval = $dateOne->diff($dateTwo);
echo $interval->format("%d " . ($interval->d > 1 || $interval->d == 0?"nights":"night"));
?>
输出:
1 night
试试这个
$checkout = date_create("2015-10-12");
$checkin = date_create("2015-10-05");
$nights = date_diff($checkout,$checkin);
print_r($nights);
你会得到这样的对象数组,
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 7
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 7
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
这是解决方案。
$checkout = $_COOKIE['cout'];
$checkin = $_COOKIE['cin'];
$datediff = strtotime($checkout) - strtotime($checkin);
$night = floor($datediff/(60*60*24));
我有 2 个字符串值,例如“24/10/2015”和“23/10/2015”,它们是动态值。我需要这两个值之间的夜间计数,所以我尝试使用 date_diff 但我无法管理它。我尝试过 strtotime、date_create_from_format 等,但没有用。有什么建议吗?
示例代码:
$checkout = $_COOKIE['cout'];
$checkin = $_COOKIE['cin'];
$nights = date_diff(strtotime($checkout),strtotime($checkin));
这应该适合你:
只需创建一个 DateTime
object with DateTime::createFromFormat()
and then you can get the difference with diff()
,像这样:
<?php
$dateOne = "24/10/2015";
$dateTwo = "23/10/2015";
$dateOne = DateTime::createFromFormat("d/m/Y", $dateOne);
$dateTwo = DateTime::createFromFormat("d/m/Y", $dateTwo);
$interval = $dateOne->diff($dateTwo);
echo $interval->format("%d " . ($interval->d > 1 || $interval->d == 0?"nights":"night"));
?>
输出:
1 night
试试这个
$checkout = date_create("2015-10-12");
$checkin = date_create("2015-10-05");
$nights = date_diff($checkout,$checkin);
print_r($nights);
你会得到这样的对象数组,
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 7
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 7
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
这是解决方案。
$checkout = $_COOKIE['cout'];
$checkin = $_COOKIE['cin'];
$datediff = strtotime($checkout) - strtotime($checkin);
$night = floor($datediff/(60*60*24));