Search code examples
phpdatediff

PHP datediff overday issue


I wish to get datediff between two times: first is in the evening (like 23:59:59) and the second is on new day (like 02:02:02). When using datediff, it doesn't show correct difference:

echo date_diff(date_create("02:02:02"), date_create("23:59:59"))->format('%H:%I:%S');
response: 21:57:57 (IS WRONG SOMEHOW)

echo date_diff(date_create("02:02:02"), date_create("00:00:00"))->format('%H:%I:%S');
response: 02:02:02 (ECHOS CORRECT TIME)

How could I get it work?


Solution

  • If the date has changed, then you have to tell it that, or it will assume today. You can check it like this:

    echo date_diff(date_create("tomorrow 02:02:02"), date_create("23:59:59"))->format('%H:%I:%S');
    // 02:02:03
    

    You can verify what the date_create is creating by just dumping it:

    var_dump(date_create("02:02:02"));
    // object(DateTime)(
    //   'date' => '2019-08-16 02:02:02.000000',
    //   'timezone_type' => 3,
    //   'timezone' => 'America/New_York'
    // )
    
    var_dump(date_create("tomorrow 02:02:02"));
    // object(DateTime)(
    //   'date' => '2019-08-17 02:02:02.000000',
    //   'timezone_type' => 3,
    //   'timezone' => 'America/New_York'
    // )
    
    var_dump(date_create("00:00:00")); // 00:00 being start of day, not end
    // object(DateTime)(
    //   'date' => '2019-08-16 00:00:00.000000',
    //   'timezone_type' => 3,
    //   'timezone' => 'America/New_York'
    // )