I am trying to calculate the difference in days between the due date of an order and today's date.
I have the following code:
function dateDiffInDays($date1, $date2) {
$diff = strtotime($date2) - strtotime($date1);
$result = abs(round($diff / 86400));
return $result;
}
When I call the function, $date1
is today and $date2
is the due date.
This works well, however if an order is overdue, that's to say $date2
is before $date1
, the function doesn't return a negative number - meaning that the order looks as if it is not overdue.
I have attempted to use an if statement within the function, to multiply the $result
by -1 $date1
is greater than $date2
, but this returns strange results and feels a bit hacky.
I am therefore looking for help in changing this function so that it returns negative values, if $date1
is before $date2
My Answer:
function dateDiffInDays($date1, $date2) {
$diff = strtotime($date2) - strtotime($date1);
$result = round($diff / 86400);
if ($date1 > $date2) {
$result *= -1;
}
return $result;
}
This updated function should now return negative values if $date1 is before $date2, indicating that the order is overdue.
Rate this post
5 of 5 based on 6227 votesComments