9

我有下面的代码行

$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 ..我将如何得到正确的答案

4

6 回答 6

15
$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;

返回$天;

这给出了正确的答案

于 2010-03-26T08:45:01.943 回答
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);
于 2010-03-25T09:01:54.420 回答
3
    $cerimonia = new Zend_Date('your date here');
    $days = $cerimonia->sub(Zend_Date::now());
    $days = round($days/86400)+1;
于 2010-08-10T15:19:23.487 回答
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);
    }
}
于 2010-06-25T13:43:06.610 回答
2

如果 $date 是 Zend_Date 对象,您可以使用以下内容:

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

或 Zend_Date 对象的其他 subXxx 函数。

于 2013-01-11T10:40:18.490 回答
0

注册日期(之后)和购买日期(之前)之间的天数

// $datePurchase instanceof Zend_Date
// $dateRegistration instanceof Zend_Date
if($datePurchase && $dateRegistration) {
   $diff = $dateRegistration->sub($datePurchase)->toValue();
   $days = ceil($diff/60/60/24)+1;
 } 
于 2011-03-23T20:51:08.820 回答