Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP format() method of DateTime modifies time

I’m trying to display a dateTime with a specific format, but it modifies the time when displayed :

$opened_at = \DateTime::createFromFormat('Y-m-d H:i:s', '2022-12-04 19:12:31');
$opened_at->setTimezone(new \DateTimeZone('Europe/Paris'));
echo $opened_at->format('d/m/Y h:i');

I’m expecting this :

04/12/2022 19:12

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But instead, I’m getting this :

04/12/2022 08:12

Why is that and how to fix this ?

>Solution :

Using the lower-case h in the format string will cause the time to be displayed in 12-hour format, with a lower-case h for the hour. This means, since 19 is greater than 12, it will be displayed as 07:12 (p.m.) in 12-hour format. This is shifted forward by an hour (to 08:12 pm) due to the timezone change.

To fix this and display the time in 24-hour format, you can use the upper-case H in the format string instead of the lower-case h. This will cause the hour to be displayed in 24-hour format, which will not be affected by the time zone. Here is an example of how to do this:

$opened_at = \DateTime::createFromFormat('Y-m-d H:i:s', '2022-12-04 19:12:31');
$opened_at->setTimezone(new \DateTimeZone('Europe/Paris')); // Timezone change offsets time to 04/12/2022 20:12:31
echo $opened_at->format('d/m/Y H:i'); // Displays "04/12/2022 20:12"

Note that you must use the upper-case H in the format string, not the lower-case h. This will ensure that the time is displayed in 24-hour format but will still be affected by the time zone.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading