2010-03-25 66 views
8

我有以下行代碼的Zend的日期 - 天差

$day1 = new Zend_Date('2010-03-01', 'YYYY-mm-dd'); 
$day2 = new Zend_Date('2010-03-05', 'YYYY-mm-dd'); 
$dateDiff = $day2->getDate()->get(Zend_Date::TIMESTAMP) - $day1->getDate()->get(Zend_Date::TIMESTAMP); 
$days = floor((($dateDiff/60)/60)/24); 
return $days; 

這將返回4

但如果給

$day1 = new Zend_Date('2010-02-28', 'YYYY-mm-dd'); 
$day2 = new Zend_Date('2010-03-01', 'YYYY-mm-dd'); 
$dateDiff = $day2->getDate()->get(Zend_Date::TIMESTAMP) - $day1->getDate()->get(Zend_Date::TIMESTAMP); 
$days = floor((($dateDiff/60)/60)/24); 
return $days; 

它將返回-27 ..怎麼會我得到正確的答案

回答

14
$firstDay = new Zend_Date('2010-02-28', 'YYYY-MM-dd'); 
$lastDay = new Zend_Date('2010-03-01', 'YYYY-MM-dd'); 
$diff = $lastDay->sub($firstDay)->toValue(); 
$days = ceil($diff/60/60/24) +1; 

回報$天;

這給正確的答案

7

我相信問題出在你的部分字符串。請嘗試使用YYYY-MM-dd

$day1 = new Zend_Date('2010-02-28', 'YYYY-MM-dd'); 
$day2 = new Zend_Date('2010-03-01', 'YYYY-MM-dd'); 
echo $day2->sub($day1)->toString(Zend_Date::DAY); 
+0

感謝邁克..這是工作...但需要減1;) – 2010-03-25 09:18:37

+5

小心'YYYY'是ISO年。今年使用'yyyy'。 – smack0007 2010-03-25 12:37:30

+0

Zend Framework Date :: sub()以秒爲單位返回差異,而不是對象toString不起作用。 – kevin 2010-07-15 08:50:25

2

我爲我自己的方便功能擴展Zend_Date。我的解決方案類似於Nisanth的,有一些關鍵的不同:

  1. 計算一天兩天的開頭比較
  2. 使用round()代替ceil()
  3. 不添加1到結果

示例代碼:

class My_Date extends Zend_Date 
{ 
    public static function now($locale = null) 
    { 
     return new My_Date(time(), self::TIMESTAMP, $locale); 
    } 

    /** 
    * set to the first second of current day 
    */ 
    public function setDayStart() 
    { 
     return $this->setHour(0)->setMinute(0)->setSecond(0); 
    } 

    /** 
    * get the first second of current day 
    */ 
    public function getDayStart() 
    { 
     $clone = clone $this; 
     return $clone->setDayStart(); 
    } 

    /** 
    * get count of days between dates, ignores time values 
    */ 
    public function getDaysBetween($date) 
    { 
     // 86400 seconds/day = 24 hours/day * 60 minutes/hour * 60 seconds/minute 
     // rounding takes care of time changes 
     return round($date->getDayStart()->sub(
      $this->getDayStart() 
     )->toValue()/86400); 
    } 
} 
3
$cerimonia = new Zend_Date('your date here'); 
    $days = $cerimonia->sub(Zend_Date::now()); 
    $days = round($days/86400)+1; 
0

號碼註冊(後)的日期和購買(前)日期

// $datePurchase instanceof Zend_Date 
// $dateRegistration instanceof Zend_Date 
if($datePurchase && $dateRegistration) { 
    $diff = $dateRegistration->sub($datePurchase)->toValue(); 
    $days = ceil($diff/60/60/24)+1; 
} 
0

如果$日期爲Zend_Date對象,你可以使用以下之間的天數:

if ($date->isEarlier(Zend_Date::now()->subDay(2)){ 
    [...] 
} 

或Zend_Date對象的其他subXxx函數。