views:

290

answers:

1

I have two Zend Date objects to work with:

$now = Zend_Date::now();
$sessionStart = new Zend_Date('2010-04-01 10:00:00', 'yyyy-MM-dd HH:mm:ss');

I need to calculate the time remaining and display in a human readable manner.

The session will begin in 7 days.
The session will begin in 30 minutes.

How can I do this with PHP and the Zend Framework?

Solution

Here's what I came up with. If you've got a better solution, please post it.

$remainingSeconds = $sessionStart->getTimestamp() - $now->getTimestamp();
// or: $remainingSeconds = $sessionStart->sub($now);
$remainingMinutes = $remainingSeconds / 60;

if ($remainingMinutes < 0) {
    //session is in the past
    return '0 days';
}

if (floor($remainingMinutes) <= 1) {
    return '1 minute';
}

if (floor($remainingMinutes) < 60) {
    return floor($remainingMinutes) . ' minutes';
}

$remainingHours = $remainingMinutes / 60;

if (floor($remainingHours) <= 1) {
    return '1 hours';
}

if (floor($remainingHours) < 24) {
    return floor($remainingHours) . ' hours';
}

$remainingDays = $remainingHours / 24;

if (floor($remainingDays) <= 1) {
    return '1 day';
}
return floor($remainingDays) . ' days';
A: 

The documentation describes this pretty good:

The methods add(), sub(), compare(), get(), and set() operate generically on dates. In each case, the operation is performed on the date held in the instance object. The $date operand is required for all of these methods, except get(), and may be a Zend_Date instance object, a numeric string, or an integer.

So:

$sessionStart->sub($now);

should do it.

How to customize the output is described in this section.

Update:
Here is an example I found on the internet:

$jan1 = new Zend_Date('1.12.2009', Zend_Date::DATES);
echo "\nJanuary first: ", $jan1->toString();

$christmas = new Zend_Date('25.12.2009', Zend_Date::DATES);
echo "\nChristmas is on: ", $christmas->toString();

$diff = $christmas->sub($jan1);
echo "\nNumber of days: ", $diff / 60 / 60 / 24;

On this site, the comment also states:

The sub() method returns the milliseconds difference between the receiver and the argument dates

Felix Kling