比较PHP中的日期


Comparing a Date in PHP

我正在开发一个php应用程序,需要一些比较日期的帮助。我有一个日期选择输入字段(日期选择器),由于客户端代码,它将始终以格式发布日期:mm/dd/YYYY,例如2015年2月25日。

我想做的是使用php确认这个日期不晚于当前日期。

最初,我设置了本地时区:

date_default_timezone_set('Europe/London');

在我的代码中:

} elseif (date(strtotime($_POST['datepicker'])) > date('m,d,Y')){
    $displayblock.= "<br><p>The selected date is in the future!!!       </p>".date("d/m/Y", strtotime($_POST['datepicker']));
$alertbox = "<script>alert('".$_POST['datepicker']." is in the future!!! Shall we try that again? :-)');</script>";

这显然远远不够优雅,而且似乎也没有正确地确定日期。有人能帮忙吗?

非常感谢,

如果它们是以字符串形式出现的,您也可以使用此函数对它们进行比较。第一个日期是来自html/javascript日期选择器的日期,第二个日期是服务器的实际日期:

function stringDateIsAPastDate($datestring1){
  if ((date("j-m-Y", strtotime($datestring1))) <= (date("j-m-Y"))){
    //here the code to do when the date inserted from the website is a past date or today
    return(true);
  }else{
    return(false);
  }
}
    $now = new DateTime();
    $now->format('Y-m-d');
    $ding = new DateTime($_POST['datepicker']);
    $ding->format('Y-m-d');
    if($now < $ding){
      echo 'datepicker is after current time';
    } else {
      echo 'datepicker is before current time';
    } 

比较两个日期

$date1 = new DateTime('May 13th, 1986');
$date2 = new DateTime('October 28th, 1989');
$difference = $date1->diff($date2);

检查此项:http://www.paulund.co.uk/datetime-php

和php.net手册:http://php.net/manual/en/class.datetime.php