繁体   English   中英

如何计算两个 Zend_Date 对象之间的差异,以月为单位

[英]how to calculate a difference between two Zend_Date objects, in months

我有Zend_Date类的两个对象,我想计算它们在完整日历月中的差异。我该怎么做?

<?php
$d1 = new Zend_Date('1 Jan 2008');    
$d2 = new Zend_Date('1 Feb 2010');
$months = $d1->sub($d2)->get(Zend_Date::MONTH);
assert($months == -25); // failure here

提前致谢!

在 Zend_Measure_Time 的帮助下,您可以轻松获得您想要的任何差异:

    $timeNow = new Zend_Date();
    $timeThen = new Zend_Date("2011-05-21T10:30:00");
    $difference = $timeNow->sub($timeThen);

    $measure = new Zend_Measure_Time($difference->toValue(), Zend_Measure_Time::SECOND);
    $measure->convertTo(Zend_Measure_Time::MONTH);

    echo $measure->getValue();

无需复杂的计算!

如果我正确阅读了文档,则没有实现以秒/分钟/.../月/年为单位获取 2 个日期之间差异的功能。 所以需要自己计算。 这样的事情会做(我不知道是否需要考虑闰年,夏令时等):

<?php
$d1 = new Zend_Date('1 Jan 2008');    
$d2 = new Zend_Date('1 Feb 2010');
$diff = $d1->sub($d2)->toValue();
$months = floor(((($diff/60)/60)/24)/30);

您可以使用简单的公式得到它:

$diffInMonth = ($startYear == $endYear) ? 
               $endMonth - $startMonth + 1 : 
               (($endYear - $startYear) * 12) - $startMonth + $endMonth + 1;

对于任何希望获得友好输出(天、小时、分钟、秒)的人,我在这里分享我的代码:

function _getDelay($since) {
    $timeNow = new Zend_Date();
    $timeThen = new Zend_Date($since);
    $difference = $timeNow->sub($timeThen);
    return $difference->toValue();
}

function _friendlySeconds($allSecs) {
    $seconds = $allSecs % 60; $allMinutes = ($allSecs - $seconds) / 60;
    $minutes = $allMinutes % 60; $allHours = ($allMinutes - $minutes) / 60;
    $hours =  $allHours % 24; $allDays = ($allHours - $hours) / 24;
    return ($allDays > 0 ? $allDays . "d" : "") .
           ($hours > 0 ? $hours . "h" : "") .
           ($minutes > 0 ? $minutes . "m" : "") . $seconds . "s";
}

只需将其称为:

echo "It happened " . _friendlySeconds(_getDelay('2010-11-18')) . " ago.";

谢谢,您的回答帮助我解决了 robertbasic 问题,这是我用来解决代码的方法:

$dob = $post ['dob'];
$date = Zend_Date::now ();
$date3 = new Zend_Date ( "$dob", 'MM.dd.yyyy' );
$diff = $date->sub ( $date3 )->toValue ();

echo $age = floor ( ((($diff / 60) / 60) / 24) / 365 );

我曾经通过计算两个 Zend 日期之间的差异来做到这一点,但这非常复杂,正如 Elzo Valugi 上面正确评论的那样。 更好地使用人的方法。 如果您的出生日期已经少了一年,则您的年龄是两个日期的年份部分之间的差值。 类似的事情可以用几个月来完成。

    function age($birthDate, $date)
    {       
        $age = $date->get(Zend_Date::YEAR) - $birthDate->get(Zend_Date::YEAR);
        $birthDay = clone $birthDate; // otherwise birthDate will be altered, objects are always passed by reference in PHP 5.3             
        $birthDay->set($date, Zend_Date::YEAR); // birthDay in the year of $date
        if (1 == $BirthDay->compare($date)) { 
            $age = $age -1; // if birth day has not passed yet
        } 
        return $age;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM