如何通过比较使用php的日期来验证日期范围


How to validate a range of date by comparing those using php?

我想显示验证错误

  1. 如果签出日期早于签入日期
  2. 如果入住日期等于明天的今天或后天错误消息
  3. 如果入住日期和退房日期相同
  4. 如果签出日期至少不晚于签入日期的一天

为此,我创建了一些变量。

$checkin_booking_period = $_POST["checkin_booking_period"];
    $checkout_booking_period = $_POST["checkout_booking_period"];
        $today = date("m.d.y");
        $dateTimestamp1 = strtotime($checkin_booking_period);
        $dateTimestamp2 = strtotime($checkout_booking_period);
        $tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));
        $day_after_tomorrow = mktime(0, 0, 0, date("m"), date("d")+2, date("y"));

我的条件声明是:

//check out date must be newer than check in date.
        if ($dateTimestamp1 > $dateTimestamp2) {
            //Blank string, add error to $errors array.        
            $errors['checkout_booking_period'] = "check out date must be newer than check in date!";
        }               
        if (($dateTimestamp1 = $tomorrow) || ($dateTimestamp1 = $day_after_tomorrow) || ($dateTimestamp1 = $today)) {
            // if checkin date is equal to today tomorrow or day after tomorrow add error message
            $errors['checkout_booking_period'] = "You have to reserve the place at least two days before the check in!";    
        }
        if ($dateTimestamp1 = $dateTimestamp2) {            
            $errors['checkout_booking_period'] = "check in date and check out date can not be same!";
        }

但这些条件语句并不能完全满足要求。例如:如果入住日期是过去的,退房日期是未来的,它会说"入住日期和退房日期不能相同!"如何创建条件语句来完全满足我上面提到的要求?

我在您的代码中看到两个问题:

1:您同时使用字符串日期和时间戳,并在条件语句中进行比较。date("m.d.y")的结果可能是"09.07.14",一个您调用$today的字符串,并将其与strtotime()产生的时间戳进行比较,如2726372362。这导致了奇怪的结果。您应该只在比较中使用时间戳。

2:您总是只能将一个值设置为$errors['checkout_booking_period'],但这不会反映在您的条件语句中。从理论上讲,可以满足不止一个条件。但不能将其存储在$errors变量中。在这种情况下,您可以编写执行效率更高的代码:

if ([condition1]) { [do something] }
elseif ([condition2]) { [do somthing else] }
elseif ([condition3]) { [do somthing else] } 
elseif ([condition4]) { [do somthing else] } 

这样,当满足第一个条件时,代码就完成了执行。当然,在这种情况下,这并不重要,但最好从一开始就学习高效的编码,并在任何地方使用它。