1

I read an article about time difference in stackoverflow URL

$datetime1 = new DateTime("2010-06-20");

$datetime2 = new DateTime("2011-06-22");

$difference = $datetime1->diff($datetime2);

echo 'Difference: '.$difference->y.' years, ' 
                   .$difference->m.' months, ' 
                   .$difference->d.' days';

print_r($difference);

This is a code to calculate time difference as you know , and i need a time diff to insert into db , but if the time diff is less than 0 years it inserts the 0 year too , how can i prevent this?

Community
  • 1
  • 1
Mark Giese
  • 11
  • 1

1 Answers1

0

Just loop over the y, m, d values with foreach, adding them if they total more than 0 in each case?

$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");

$difference = $datetime1->diff($datetime2);

$description = [];
foreach (["year", "month", "day"] as $unit) {
    $value = $difference->{substr($unit, 0, 1)};
    switch ($value) {
        case 0: break;
        case 1: $description[] = "1 $unit"; break;
        default: $description[] = "$value {$unit}s"; break;
    }
}
echo "Difference: " . implode(", ", $description);
Matt Raines
  • 4,149
  • 8
  • 31
  • 34