我有两个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
提前致谢!
答案 0 :(得分:16)
在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();
无需复杂的计算!
答案 1 :(得分:13)
如果我正确阅读了文档,则没有实现两个日期之间的差异,以秒/分钟/.../个月/年为单位,因此您需要自己计算。这样的事情会发生(dunno,如果需要闰年,DST等等):
<?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);
答案 2 :(得分: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.";
答案 3 :(得分:1)
谢谢,你的回答帮助我解决了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 );
答案 4 :(得分:1)
您可以使用简单的公式获得它:
$diffInMonth = ($startYear == $endYear) ?
$endMonth - $startMonth + 1 :
(($endYear - $startYear) * 12) - $startMonth + $endMonth + 1;
答案 5 :(得分:0)
我曾经通过两个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;
}