Say I have this:
$date1=date_create(date('H:I', strtotime('8:00')));
$date2=date_create(date('H:I', strtotime('18:00')));
$diff1=date_diff($date1,$date2);
echo $diff1->format("%h:%I");
which outputs 10:00 (hours), but now i want to compare this:
$date3=date_create(date('H:I', strtotime('8:30')));
$date4=date_create(date('H:I', strtotime('17:45')));
$diff2=date_diff($date3,$date4);
echo $diff2->format("%h:%I");
which outputs 9:15
. So, how can I have the diff and the sign (if it's negative) between $diff1
and $diff2
? I just want to get that 45 minutes negative (in this case).
You can use %r
to format to print if the difference is negative:
$diff1 = date_diff(date_create(date('H:i', strtotime('20:00'))), date_create(date('H:i', strtotime('18:00'))));
echo $diff1->format("%r%H:%i"); // prints -02:00
$diff2 = date_diff(date_create(date('H:i', strtotime('8:30'))), date_create(date('H:i', strtotime('17:45'))));
echo $diff2->format("%r%H:%i"); // prints 09:15
A better version:
$diff1 = date_diff(DateTime::createFromFormat('H:i', '20:00'), DateTime::createFromFormat('H:i', '18:00'));
echo $diff1->format("%r%H:%i"); // prints -02:00
$diff2 = date_diff(DateTime::createFromFormat('H:i', '8:30'), DateTime::createFromFormat('H:i', '17:45'));
echo $diff2->format("%r%H:%i"); // prints 09:15
Read more about DateTime.
Think with this could go:
$date5=date_create(date('H:i', strtotime($diff1)));
$date6=date_create(date('H:i', strtotime($diff2)));
$diff3=date_diff($date5,$date6);
echo $diff3->format("Final: %h:%I");