0

I need to find the difference in minutes between these two dateTime in such format which is written. I get this error, please help:

Uncaught Exception: DateTime::__construct(): Failed to parse time string (27/09/2020 01:00:19 AM) at position 0 (2):

$datetime1 = new DateTime('27/09/2020 01:00:19 AM');
                            $datetime2 = new DateTime('27/09/2020 01:00:19 AM');
                            $interval = $datetime1->diff($datetime2);
                            echo $interval->format('%hh %im');
Cid
  • 14,968
  • 4
  • 30
  • 45

2 Answers2

1

When parsing date formats, php follows specific rules :

If the date separator is /, then php will try to use either the American format mm/dd/y or the notation YY/mm/dd

You can specify the date/time format while creating the object using DateTime::createFromFormat() :

$datetime1 = DateTime::createFromFormat('d/m/Y g:i:s a', '27/09/2020 01:00:19 AM');
$datetime2 = DateTime::createFromFormat('d/m/Y g:i:s a', '27/09/2020 01:00:19 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh %im');

This outputs :

0h 0m

Fiddle

Cid
  • 14,968
  • 4
  • 30
  • 45
  • 1
    Perhaps add the why: PHP is considering dates with `/` as `m/d/y` and with `-` as `d-m-y` formatted. So `27/09/2020` is parsed as month = 27, day = 9, year = 2020. And there obviously isn't a month 29 – Michel Sep 29 '20 at 09:22
  • while changing the datetime2 to 28/09/2020 01:00:19 AM then it does not give any result. Means while different dates – user3153807 Sep 29 '20 at 10:03
  • @user3153807 that's because you're only displaying the hours and minutes of the differences, not the days. This is a whole different question – Cid Sep 29 '20 at 11:09
0

You can do like this:

$datetime1 = new DateTime(str_replace('/','-','27/09/2020 01:00:19 AM'));
$datetime2 = new DateTime(str_replace('/','-','27/09/2020 01:00:19 AM'));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh %im');