比较h:ia时间格式字符串php - 不工作

时间:2017-12-22 05:57:26

标签: php datetime datetime-format

示例,我的tmp数组是:

Array
(
    [checkin] => 11:00am
    [checkout] => 12:00pm
    [day_from] => 09:59am
    [day_to] => 06:00pm
)

我使用下面的代码来比较时间,但在这两种情况下它总是会显示' hello'即使是签到时间和结账时间都在日内和日期之间。

实际上,这个功能是检查客人的登记和结账时间是否在餐厅开放时间为几小时?

任何帮助将不胜感激!在此先感谢: - )

$tmp_arr = array();
$tmp_arr['checkin'] = $checkin = date('h:ia',strtotime($checkin));
$tmp_arr['checkout'] = $checkout = date('h:ia',strtotime($checkout));
$tmp_arr['day_from'] = $day_from = date('h:ia',strtotime($day_from));
$tmp_arr['day_to'] = $day_to = date('h:ia',strtotime($day_to));
print_r($tmp_arr);
if($checkin>=$day_from && $checkin<=$day_to){
    echo "hi";
}
else{
    echo "hello";
}
if($checkout>=$day_from && $checkout<=$day_to){
    echo "hi";
}
else{
    echo "hello";
}

1 个答案:

答案 0 :(得分:0)

您应该使用strtotime将时间字符串转换为unix时间戳。然后你可以按照预期的方式对它们进行比较。

$checkin = '11:00am';
$checkout = '12:00pm';
$day_from = '09:59am';
$day_to = '06:00pm';

$tmp_arr = array();
$tmp_arr['checkin'] = $checkin = strtotime($checkin);
$tmp_arr['checkout'] = $checkout = strtotime($checkout);
$tmp_arr['day_from'] = $day_from = strtotime($day_from);
$tmp_arr['day_to'] = $day_to = strtotime($day_to);
print_r($tmp_arr);
if($checkin>=$day_from && $checkin<=$day_to){
    echo "hi";
}
else{
    echo "hello";
}
if($checkout>=$day_from && $checkout<=$day_to){
    echo "hi";
}
else{
    echo "hello";
}