dongshi3361 2014-12-04 09:57
浏览 27
已采纳

PHP日期比较(2周)

$todaysDate = date("Y-m-d");
$maxBookingDate=strtotime('+2 weeks', $todaysDate);
$dateEntered = DateTime::createFromFormat('d/m/Y', $_POST["Date"]);
$tableDate =$dateEntered->format('Y-m-d');
if ($tableDate < $todaysDate){
    echo "Date must be in the future";
}
if ($tabledate > $maxBookingDate){
    echo "Date must be no more than 2 weeks in advance";
}

Date comparison to make sure that the date a user enters is no more than two weeks in advance isn't working, what have I done wrong?

  • 写回答

1条回答 默认 最新

  • dtvpe4837413 2014-12-04 10:03
    关注

    You can just use DateTime classes all through out so that its easier to compare:

    $todaysDate = new DateTime();
    $maxBookingDate = new DateTime('+2 weeks');
    $dateEntered = DateTime::createFromFormat('d/m/Y', $_POST['Date']);
    if ($dateEntered < $todaysDate){
        echo "Date must be in the future";
    } elseif ($dateEntered > $maxBookingDate){
        echo "Date must be no more than 2 weeks in advance";
    }
    

    In your code:

    $todaysDate is a string, and you fed it inside strtotime() as your second parameter which is incorrect usage. The second parameter requires numeric value (timestamp).

    Inside your if else statement, you're comparing strings. You should be comparing them as timestamps or DateTime objects instead, like the answer above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度