I am trying to calculate difference between two dates in days, here are the two dates:
$date_1 = "2017-06-12 13:44:58";
$date_2 = "2017-05-04 19:06:24";
When I do it through PHP script it gives 38 as result, which is correct.
$datediff = strtotime($date_1) - strtotime($date_2);
echo floor($datediff / (60 * 60 * 24));
Result: 38 ----> Correct
Because there is still difference in hours of the given dates
But when I do the same in MySQL, then it gives 39 as result, which is wrong.
select DATEDIFF("2017-06-12 13:44:58","2017-05-04 19:06:24")
Result: 39 ----> Incorrect
From MySQL help:
DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
You can use TIMESTAMPDIFF
instead:
select ABS(TIMESTAMPDIFF(DAY,"2017-06-12 13:44:58","2017-05-04 19:06:24"));
+---------------------------------------------------------------------+
| ABS(TIMESTAMPDIFF(DAY,"2017-06-12 13:44:58","2017-05-04 19:06:24")) |
+---------------------------------------------------------------------+
| 38 |
+---------------------------------------------------------------------+
You can do something like this :
SELECT FLOOR(ABS(TIMESTAMPDIFF(HOUR, "2017-06-12 13:44:58","2017-05-04 19:06:24") / 24));
TIMESTAMPDIFF(HOUR...)
will get the difference in hour so we have to divide it by 24 to get the difference in days.
The ABS
is to avoid to have a negative number.