Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent for MySQL's DATEDIFF

I have a problem with date comparing logic in MySQL and PHP: date difference functions return different results for the same dates. Example:

SQL

SELECT DATEDIFF('2024-06-02', '2024-05-03 12:57')
30

PHP

$x = date_diff( new DateTime( '2024-06-02' ), new DateTime( '2024-05-03 12:57' ) );

enter image description here

This is causing an assertion error when I pass data selected from the DB with the where DATEDIFF... criteria to PHP that checks the date with the date_diff() function.

Is there a strict equivalent for MySQL function in PHP (or vice versa), so that both return 29 (or 30)?

like image 996
Anton Duzenko Avatar asked Dec 22 '25 06:12

Anton Duzenko


1 Answers

Both should return 30 but the PHP code you have written doesn't account for time so it reports 29.

If you normalize both to midnight, it will report 30 days.

echo $x = date_diff( 
    (new DateTime( '2024-06-02' ))->setTime(0,0), 
    (new DateTime( '2024-05-03 12:57' ))->setTime(0,0) 
)->days;
// Outputs: 30
like image 143
Dharman Avatar answered Dec 23 '25 20:12

Dharman