php中的日期差异自定义输出

Here is my php code. It is working fine.

<?php
........
    $cdt1 = Date("Y-m-d H:i:s");            

    $last_seen = "2015-05-20 12:15:20";

    $datetime22 = new DateTime($cdt1);

    $datetime11 = new DateTime($last_seen);

    $interval1 = $datetime11->diff($datetime22);

echo $interval1->format('%y years %m months and %d days %H hours, %i min and %s sec ');
.........
?>

It is giving me output like this. 0 years 0 months 0 days 00 hours 1 min and 52 sec. Something like that.

I want

  if year is 0 then year doesn't show.
  if month is 0 then month doesn't show.
  if days is 0 then days doesn't show.
  same for hour and min as well.

e.g if difference of time is 1 hour 24 min 30 sec then it should appear like 1 hour 24 min 30 sec. I don't want year/month/days if they are 0.

Please advise.

One option could be using a regular expression:

$date = $interval1->format('%y years %m months and %d days %H hours, %i min and %s sec ');

$replaced = false;
while ($replaced)
{
    $date = preg_replace('/^(0 [a-z]+)/', '', ltrim($date, " ,and"), 1, $replaced);
}

Notice the ^ character showing the beginning of the regular expression, the fourth parameter to make only one replacement at a time and the fith one to use it as a bool (integer) flag in the while.

if you convert DateInterval object to array and then use array_filter() plus array_intersect_key() you can see the values of years, months, days, hours, minutes & seconds with non-zero respectively. So then you can set format on that as you wish.

    $cdt1 = Date("Y-m-d H:i:s");            
    $last_seen = "2015-05-20 12:15:20";
    $datetime22 = new DateTime($cdt1);
    $datetime11 = new DateTime($last_seen);
    $interval1 = $datetime11->diff($datetime22);
    //print_r($interval1);

    $allowed = array('y', 'm' , 'd', 'h', 'i', 's');
    echo '<pre>';
    print_r(array_filter(array_intersect_key((array)$interval1, array_flip($allowed))));

OUTPUT

 Array
(
    [d] => 10
    [h] => 17
    [i] => 25
    [s] => 55
)

SEE http://codepad.viper-7.com/Zliglz

I got help from diafol(daniweb). https://www.daniweb.com/web-development/php/threads/496432/date-diff-customized-output-in-php

Here is the answer.

function from_now($date)
{
    $datetime22 = new DateTime();
    $datetime11 = new DateTime($date);
    $interval1 = $datetime11->diff($datetime22);
    $str = $interval1->format('%y,%m,%d,%h,%i,%s');
    $names = ['years','months','days','hours','min','sec'];
    $r = explode(',',$str);
    $output = [];
    for($i=0;$i<6;$i++) if($r[$i] != 0 || $i == 5) $output[] = $r[$i] . ' ' . $names[$i];
    return implode(', ', $output);
}
echo from_now("2015-05-20 12:15:20");