douqi3195 2014-08-30 04:07
浏览 44
已采纳

检查时间变量以确保其少于30天但不低于当前时间

I'm trying to check my string $when to ensure it's not 30 days+ into the future based on the current time(), but also not less than the current time(). For some reason strtotime is causing some sort of issue. Any suggestions on how to make this script function?

<?php
$when = '2011/07/11 11:22:52';

if ($when > strtotime('+30 days', time()));
{
echo "too far into the future";
header('Refresh: 10; URL=page.php');
die();
}

if ($when < time());
{
echo "less than current time";
header('Refresh: 10; URL=page.php');
die();
}

echo "pass";
header('Refresh: 10; URL=page.php');
die();
?>
  • 写回答

1条回答 默认 最新

  • dsvd407787736 2014-08-30 04:12
    关注

    Your issue is you're comparing a date string to a Unix Timestamp. You need to convert $when to a Unix Timestamp before doing your comparisons:

    $when = strtotime('2011-07-11 11:22:52');
    

    I find using DateTime() makes this easy and readable (and also handles things like daylight savings time):

    $when   = new DateTime('2011-07-11 11:22:52');
    $now    = new DateTime();
    $future = new DateTime('+30 days');
    
    if ($when > $future )
    {
    echo "too far into the future";
    header('Refresh: 10; URL=page.php');
    die();
    }
    
    if ($when < $now)
    {
    echo "less than current time";
    header('Refresh: 10; URL=page.php');
    die();
    }
    
    echo "pass";
    header('Refresh: 10; URL=page.php');
    die();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?