0

My Question is Little bit tricy . i have to display date difference. (i find out date difference in terms of 2 year 7 month 3 days 5 hrs 30 min.)

Now how i display upto exact 2 higher values please consider given case

case 1 : date difference is 0 year 2 month 21 days 7 hrs 30 min
output must be : 2 Month 21 days

case 2 : 0 year 0 month 0 days 7 hrs 20 min
output must be : 7 hours 21 days

4

2 Answers 2

0

If your date differences is in the exact form as in your question (separated with " ") and formatted as strings. This will do the trick.

<?php
function display_times($string){
    $pieces = explode(" ",$string);

    $num_disp = 0;
    foreach($pieces as $i => $pice){
        if(is_numeric($pice) && intval($pice) != 0){
            echo $pice." ".$pieces[$i+1]." ";
            $num_disp++;
            if($num_disp >= 2) break;
        }
    }
}

$case1 = "0 year 2 month 21 days 7 hrs 30 min";
$case2 = "0 year 0 month 0 days 7 hrs 20 min";

display_times($case1);
echo PHP_EOL;
display_times($case2);

?>
0

You can modify this function. Replace 3rd parameter with $depth and modify array_slice line, like on demo.

Use examples :

echo time_diff_string('2013-05-01 00:22:35', 'now', 1), "\n";
echo time_diff_string('2013-05-01 00:22:35', 'now', 2), "\n";
echo time_diff_string('2013-05-01 00:22:35', 'now', 3), "\n";
echo time_diff_string('2013-05-01 00:22:35', 'now', 4), "\n";

Output :

6 months ago
6 months, 6 days ago
6 months, 6 days, 12 hours ago
6 months, 6 days, 12 hours, 6 minutes ago

Demo.

Not the answer you're looking for? Browse other questions tagged or ask your own question.