user3153807
user3153807

Reputation: 11

Difference of minute between two dateTime

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');

Upvotes: 0

Views: 43

Answers (2)

Cid
Cid

Reputation: 15257

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

Upvotes: 1

Kaiser Ahmed Tushar
Kaiser Ahmed Tushar

Reputation: 46

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');

Upvotes: 0

Related Questions