如何比较php

时间:2016-07-30 12:20:43

标签: php arrays date-comparison

我有两个已经预订的开始和结束日期

<?php
$arr2 = range(strtotime($_POST['start']), strtotime($_POST['end']), "86400");
//$arr2 = range(strtotime($row['check_out_date']),strtotime($row['check_in_date']), "86400");
//echo $arr1; 
array_walk_recursive($arr2, function(&$element) {
  $element = date("j-n-Y", $element);
});
//array_walk_recursive($arr2, function(&$element) { $element = date("d-n-Y", $element); });
$es = array();
//array_push($events, $e);
$name = json_encode($es);
//echo $name;    
foreach ($arr2 as $values) {
  $arr4[] = $values;
  echo $values;
}
?>

在arr4 []我得到的日期已经预订,如b / w 1-3所有日期,同样我得到该用户想要预订日期,

如何比较这两个日期,并匹配日期是否匹配,然后显示警报日期匹配,否则执行插入查询,所以请帮助。

2 个答案:

答案 0 :(得分:0)

有几种方法可以比较PHP中的日期,但我使用的方法是使用PHP的内置DateTime类:

<?php
$timezone = new DateTimezone('America/Chicago');
$start = DateTime::createFromFormat('Y-m-d H:i:s','2016-01-01 00:00:00',$timezone);
$end = DateTime::createFromFormat('Y-m-d H:i:s','2016-02-02 00:00:00',$timezone);
// PHP 5.2.2 allows you to compare dates using differential operators
// Otherwise use DateTime::diff, http://php.net/manual/en/datetime.diff.php
if($start == $end){
    echo "Same!\n";
}
else {
    echo "Not Same!\n"
}
?>

答案 1 :(得分:-1)

这是我的忠诚 该函数返回一个日期不同的子句

您可以通过2种方式比较某个日期和当前

timeDiff('123556568') // time()

timeDiff('20-6-2020') // any date format

timeDiff('20-6-2020','20-2-2120') // two dates 

timeDiff('143556568','123556568') // two dates 



    function timeDiff($time2_, $time1_ = false) {
            $date1 = new \DateTime();
            if ($time1_) {
// check if it timestamp or not 
                $time1 = preg_match('/[-\/]/', $time1_) ? strtotime($time1_) : $time1_;
                $date1->setTimestamp($time1);
            }
            $date2 = new \DateTime();
            $time2 = preg_match('/[-\/]/', $time2_) ? strtotime($time2_) : $time2_;
            $date2->setTimestamp($time2);
            $interval = $date1->diff($date2);
// get diffrence
            $diffrent_ = $interval->format('%Y Years %m Months %d Days %H:%I:%S');
// clean from zero values

            $diffrent = str_replace(['00 Years', ' 0 Months', ' 0 Days', '00:00:00'], '', $diffrent_);
// some change for 01 & s
            $returner = str_replace(['01 Years', ' 1 Months', ' 1 Days'], ['01 Year', ' 1 Month', ' 1 Day'], $diffrent);
            return trim($returner);
        }