日期不是今天或之前,也不会超过今天检查php

时间:2014-05-07 19:23:21

标签: php date compare

如果符合以下任何条件,我需要检查并给出错误: 用户选择的日期是:

  • 今天的OR
  • 今天之前的OR
  • 从今天起1年后

我正在检查此代码

if((strtotime($_POST["sch_date"])<=strtotime(date("d/m/Y"))) OR (((strtotime(date("d/m/Y",strtotime("+1 year"))))-(strtotime($_POST["sch_date"])))/(60*60*24)<0))

但这会给出偶然的结果,这意味着如果所选日期少于1年,则会显示错误。有人可以建议如何解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

使用DateTime()可以轻松实现,因为它们具有可比性:

$dateSelected   = DateTime::createFromFormat('d/m/Y', '18/04/2014'); // put your date here
$today          = new DateTime();
$oneYearFromNow = new DateTime('+1 year');
if ($dateSelected <= $today && $dateSelected > $oneYearFromNow) {
    // we're good
}
else {
    // it's the end of the world!
}

答案 1 :(得分:0)

你的尝试非常接近,可能只是有点过于复杂,试试这个:

date_default_timezone_set('America/Los_Angeles'); // Set your timezone

// Assuming $_POST['sch_date'] is in the form 'd/m/Y'
$date = str_replace('/', '-', $_POST['sch_date']);

if (strtotime($date) <= strtotime('today') || strtotime($date) > strtotime('+ 1 year'))
    echo "error";

注意:这假定$date是某种标准格式的日期 - m/d/Yd-m-YY-m-d等,但不是日期时间。请参阅here for standard formats如果$date,则会出错 今天或今天之前的任何日期,或$date是否在今天之后的1年之后。

要转换您的非标准d/m/y,您需要将其添加到上面的代码中:

$date = str_replace('/', '-', $_POST['sch_date']);