2014-11-15 35 views
1

如何檢查是生日是在本週,2周或月內我使用下面的代碼來檢查,但它返回錯誤的計算。檢查upcomming生日在一個星期2周或在一個月內使用php

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

你想檢查'$ birthdate'是否在下一個'$ days'天? –

+0

我想查看出生日期是否在'$ days'內 – magelearner

回答

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; 
} 

demo

+0

感謝兄弟你讓我的一天 – magelearner

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()。這改變了答案是準確的。 正在完成的另一種方式是使$倒數成爲一個巨大的負數。

相關問題