0

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.

Edited by md.Rayad: code not showing

2
Contributors
1
Reply
11
Views
2 Years
Discussion Span
Last Post by diafol
1

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");
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.