PHP 检查日期是今天还是未来最多 7 天


PHP Checking if the date is today or up to 7 days in future

我正在尝试解决一个所谓的基本问题。我想检查用户是否输入了有效日期。我们申请中的有效日期是今天或未来 7 天。因此,该范围内的任何日期都是有效的。过去或从现在起的第7天起的任何日期将被视为无效。

我写了一个小函数来解决这个问题:

function is_valid($d)
{
if( strtotime($d) < strtotime('+7 days') ) {
return true;
}
else return false;
}
Usage : is_valid('01-20-2015');  //M-D-Y

但这总是回归真实。

我做错了什么?

艾哈迈尔

正如注释中所述 - 您不认为strtotime()无法解析输入的日期(无效的日期格式等)。

试试这个代码:

function is_valid($d)
{
   if( strtotime($d) !== FALSE && strtotime($d) < strtotime('+7 days') ) {
      return true;
   }
   return false;
}
Usage : is_valid('01-20-2015');  //M-D-Y

您还应该记住,strtotime取决于服务器的时区,如文档中所述。

使用 DateTime 函数要容易得多。

$yourDate = new 'DateTime('01-20-2015');
// Set 00:00:00 if you want the aktual date remove the setTime line
$beginOfDay = new 'DateTime();
$beginOfDay->setTime(0,0,0);
// Calculate future date
$futureDate = clone $beginOfDay;
$futureDate->modify('+7 days');
if($yourDate > $beginOfDay && $yourDate < $futureDate) {
    // do something
}

strtotime无法解析该日期格式。您需要使用 YYYY-MM-DD

使用此测试代码进行确认;

<?php
function is_valid($d) {
   if (strtotime($d) < strtotime('+7 day')) {
      return true;
   }
   else 
      return false;
}
var_dump(is_valid('2015-12-25'));
// Wrong format;
echo "Right: " . strtotime('2015-12-25') . "'n";
// Right format;
echo "Wrong: " . strtotime('01-20-2015') . "'n";

可以在这里看到;http://codepad.org/iudWZKnz