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.

Member Avatar for diafol

Maybe something like this:

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");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.