Php 检查时间变量,确保其小于30天但不小于当前时间
我正在尝试检查字符串$when,以确保它不是基于当前时间()的未来30天以上,但也不小于当前时间()。由于某种原因,strotime引发了某种问题。关于如何使这个脚本发挥作用,有什么建议吗Php 检查时间变量,确保其小于30天但不小于当前时间,php,date,strtotime,Php,Date,Strtotime,我正在尝试检查字符串$when,以确保它不是基于当前时间()的未来30天以上,但也不小于当前时间()。由于某种原因,strotime引发了某种问题。关于如何使这个脚本发挥作用,有什么建议吗 <?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
<?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');
我发现使用户可以轻松阅读(还可以处理诸如夏令时之类的事情):
$when=新日期时间('2011-07-11 11:22:52');
$now=新日期时间();
$future=新日期时间(“+30天”);
如果($when>$future)
{
呼应“太遥远的未来”;
标题('Refresh:10;URL=page.php');
模具();
}
如果($when<$now)
{
回显“小于当前时间”;
标题('Refresh:10;URL=page.php');
模具();
}
呼应“通行证”;
标题('Refresh:10;URL=page.php');
模具();
$when是字符串“2011/07/11 11:22:52”,但如果要比较这两个变量,它应该是一个int,就像从strotime获得的时间戳一样。调用DateTime()时添加时区信息不是也很重要吗?我在一个php文件中运行了它,它说2011/07/11 11:22:52太遥远了,而它应该说少于当前时间。知道为什么吗?谢谢你的帮助!(编辑:是的,它仍然说太远了)我认为它默认为服务器timezone@derp你知道这个脚本有什么问题吗?见我上面的评论
$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();