如何检查是生日是在本周,2周,还是月份我用下面的代码检查但是它返回了错误的计算。
public function CountDown($birthdate, $days=7)
{
list($y,$d,$m) = explode('/',$birthdate);
$today = time();
$event = mktime(0,0,0,$m,$d,$y);
$apart = $event - $today;
if ($apart >= -86400)
{
$myevent = $event;
}
else
{
$myevent = mktime(09,0,0,$m,$d,$y);
}
$countdown = round(($myevent - $today)/86400);
if ($countdown <= $days)
{
return true;
}
return false;
}
答案 0 :(得分:1)
试试这个:
function CountDown($birthdate, $days=7)
{
# create today DateTime object
$td = new DateTime('today');
# create birth DateTime object, from format Y/d/m
$bd = DateTime::createFromFormat('!Y/d/m', $birthdate);
# set current year to birthdate
$bd->setDate($td->format('Y'), $bd->format('m'), $bd->format('d'));
# if birthdate is still in the past, set it to new year
if ($td > $bd) $bd->modify('+1 year');
# calculate difference in days
$countdown = $bd->diff($td)->days;
# return true if day difference is within your range
return $countdown <= $days;
}
答案 1 :(得分:0)
这对我有用
class Birthday{
public function CountDown($birthdate, $days=7)
{
list($y,$d,$m) = explode('/',$birthdate);
$today = time();
$event = mktime(0,0,0,$m,$d,$y);
$apart = $event - $today;
if ($apart >= -86400)
{
$myevent = $event;
}
else
{
$myevent = mktime(09,0,0,$m,$d);
}
$countdown = round(($myevent - $today)/86400);
if (($countdown <= $days))
{
return true;
}
return false;
}
}
$bday = new Birthday;
$count = $bday->CountDown("1969/16/11"); //today is 2014/14/11
var_dump($count); //returns true.
我刚从$ myevent中的mktime()中删除了年份。这改变了答案是准确的。 另一种方式是将倒数计算成一个巨大的负数。