【问题标题】:Date not today or before and not more than year from today check php日期不是今天或之前,从今天起不超过一年检查php
【发布时间】:2014-05-07 19:23:21
【问题描述】:

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

  • 今天的 OR
  • 在今天的 OR 之前
  • 从今天起一年后

我正在检查这段代码

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 天,它会显示错误。有人可以建议如何解决这个问题吗?

【问题讨论】:

    标签: php date compare


    【解决方案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!
    }
    

    【讨论】:

    • 嗨,我使用的是 d/m/Y 格式。那么我应该为选定日期new DateTime($_POST["sch_date"]) 和当前日期new DateTime('d/m/Y') 写一些类似的东西吗?
    • 您需要使用DateTime::createFromFormat() 来确保日期不模糊。我会相应地更新我的答案。
    • thnks @John Conde 这看起来有效。但我会更广泛地尝试并检查
    【解决方案2】:

    您的尝试非常接近,也许只是有点过于复杂,试试这个:

    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 是从今天起一年之后。

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

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

    【讨论】:

    • 喜仍然无法预测的结果。即使在 13/03/2015 时也会出现错误。也许还有其他事情发生了。我可以强制选择日期的格式吗?我是从 javascript 中获取的
    • 编辑 - 是的,你是对的。只是在测试这个,它似乎将d/m/Y 转换为m/d/Y,所以也许你需要指定。我正在运行更多测试...
    • @user2649343 请注意我的编辑。鉴于d/m/Y 的格式,这现在应该对您有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2014-09-13
    相关资源
    最近更新 更多