2

I am using this to create a string with the difference between dates:

$startDate = DateTime::createFromFormat(self::$timeFormat, $startDate);
$difference = $startDate->diff($endDate);

$dateTimeElapsed = $difference->format('%y years %m months %a days %h hours %i minutes %S seconds');

return $dateTimeElapsed;

And that would output something like: 0 years 0 months 0 days 0 hours 0 minutes 27 seconds

How can I code it so I can remove any zero values such as 0 years, months etc...

Erdss4
  • 1,025
  • 3
  • 11
  • 31

2 Answers2

1

Sorted out with

$dateTimeElapsed = $difference->format('%y|%m|%a|%h|%i|%S');

$outPuts = [
    "years", "months", "days", "hours", "minutes", "seconds"
];

$explodedDateString = explode("|", $dateTimeElapsed);

$dateTimeElapsed = array_combine($outPuts, $explodedDateString);

$finalDateDiff = 0;
foreach($dateTimeElapsed as $string => $value)
{
   if($value > 0)
   {
      if($value == 1)
      {
        $string = substr($string, 0, -1);
      }
       $finalDateDiff = $value . " " . $string;
       break;
    }
}

return $finalDateDiff;

Works by only outputting the closest value which is more than zero. Used explode to put the diff values into an array. Combine both arrays together so that the string names "years, months" etc match up with their values and then user a foreach to check if the value is over 0.

Returns 0 is there is not match or all values are 0.

EDIT: Updated the code so that when the difference is 1 year, 1 month, 1 days etc... It removes the 's' of the end to make it grammatically correct.

Erdss4
  • 1,025
  • 3
  • 11
  • 31
0

A simple solution would be to use the diffForHumans() function from the php Carbon class :

$dt = Carbon::createFromFormat('Y-m-d H:i:s', '2017-01-22 15:30:00');   
echo $dt->diffForHumans();

output :

3 months ago

diffForHumans() documentation on carbon.nesbot.com

JazZ
  • 4,469
  • 2
  • 20
  • 40