-4

i am trying to display 'Days' and 'hours' code is working fine, but issue is i don't want to show 0 days. if day= 0 then show only hours.

<?php
  $datetime1 = new DateTime();
  $datetime2 = new DateTime($feed['dt_date_added']);
  $interval = $datetime1->diff($datetime2);
  $elapsed = $interval->format('%a days %h hours'); 
  echo $elapsed;
?>

Output : - 0 Days 5 Hour

Expected Output: 5 Hour

ADyson
  • 57,178
  • 14
  • 51
  • 63

2 Answers2

1

You can just check whether the number of days is 0 or not, and adjust your output format accordingly. The DateInterval object provides the "d" property which lets you see the number of days (see documentation).

$datetime1 = new DateTime();
$datetime2 = new DateTime($feed['dt_date_added']);
$interval = $datetime1->diff($datetime2);
$format = "%h hours";
if($interval->d > 0) $format = "%a days ".$format; //adjust the format according to the number of days
$elapsed = $interval->format($format); 
echo $elapsed;

Demo: http://sandbox.onlinephpfunctions.com/code/d01ae70566b1b4466664fcff8f7c70b261766c48

ADyson
  • 57,178
  • 14
  • 51
  • 63
0

You just have to check if the days are 0:

   $datetime1 = new DateTime();
   $datetime2 = new DateTime($feed['dt_date_added']);
   $interval = $datetime1->diff($datetime2);
   $elapsed = $interval->format( $interval->format('%a') ? '%a days %h hours' : '%h hours'  ); 
   echo $elapsed;
Elanochecer
  • 600
  • 3
  • 8