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


check time variable to ensure its less than 30 days but not less than the current time

我正在尝试检查我的字符串$when,以确保它不是基于当前时间()的未来30天以上,但也不小于当前时间(。由于某种原因,strtotime导致了某种问题。关于如何使这个脚本发挥作用,有什么建议吗?

<?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();
?>

您的问题是将日期字符串与Unix时间戳进行比较。在进行比较之前,您需要将$when转换为Unix时间戳:

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

我发现使用DateTime()使它变得简单易读(还可以处理夏令时等问题):

$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();