...

HELP Display different times for hours.

Vernk
10-06-2012, 06:42 AM
DB
User | Hours
1 13
2 982
3 145
4 200

So say for User 2 is 982 which is 40.916 days I want to display it like this:
1 Month 10 days 9 hours
And user 3
145 - 6.0416 Days Display:
6 Days 42 minutes
User 4
200 - 8.33 days
1 Week 1 day 3 hours

etc for years also

Vernk
10-07-2012, 02:04 AM
I know it seems complicated but can anyone try an attempt?

Len Whistler
10-07-2012, 04:07 AM
The function below should be OK. Some of the results are different than yours so it might need fine tuning.

<?php

function elapsed_time(\$seconds, \$precision = 2) {

\$a = array('decade' => 315576000, 'year' => 31557600, 'month' => 2629800, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'min' => 60, 'sec' => 1);
\$i = 0;
foreach(\$a as \$k => \$v) {
\$\$k = floor(\$seconds/\$v);
if (\$\$k) \$i++;
\$seconds = \$i >= \$precision ? 0 : \$seconds - \$\$k * \$v;
\$s = \$\$k > 1 ? 's' : '';
\$\$k = \$\$k ? \$\$k.' '.\$k.\$s.' ' : '';
@\$result .= \$\$k;
}

return \$result;
}

\$hours=13;
\$seconds =(\$hours*3600);
echo elapsed_time(\$seconds, 6).'<br />';

\$hours=982;
\$seconds =(\$hours*3600);
echo elapsed_time(\$seconds, 6).'<br />';

\$hours=145;
\$seconds =(\$hours*3600);
echo elapsed_time(\$seconds, 6).'<br />';

\$hours=200;
\$seconds =(\$hours*3600);
echo elapsed_time(\$seconds, 6).'<br />';

?>

Ouput
13 hours
1 month 1 week 3 days 11 hours 30 mins
6 days 1 hour
1 week 1 day 8 hours

Fou-Lu
10-07-2012, 03:07 PM
They're different because your numbers are accurate (-ish, minus the month one which simply cannot be calculated properly). Since these are in hours with no indication of a fraction available, there is therefore no way to generate any time block < 1 hour in size (so no minutes and no seconds).

There is of course no accurate way to perform this without knowing the starting date. Month is an ambiguous term with days qualifying as anywhere between 28 and 31 (72 hour variation). This is the same reason why things like DateInterval also cannot perform roll-overs as it could determine 32 days as anywhere between 1 month and 1 day or 1 month and 4 days.