日期不是今天或以前,不超过一年从今天检查php


Date not today or before and not more than year from today check php

如果这些条件中的任何一个为真,我需要检查并给出错误:用户选择的日期为:

    今天
  • 今日或之前
  • 即日起一年后

我正在检查这个代码

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))

,但这给随机结果意味着它显示错误,如果选择的日期是2天少于1年。有人能告诉我该怎么做吗?

使用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!
}

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

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等,但不是日期时间。如果$date是,将给出一个错误今天或今天之前的任何日期,或者$date是从今天起一年后。

要转换您的非标准d/m/y,您需要这个,它已添加到上面的代码中:

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