Home > Software engineering >  PHP format() method of DateTime modifies time
PHP format() method of DateTime modifies time

Time:12-05

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

But instead, I'm getting this :

04/12/2022 08:12

Why is that and how to fix this ?

CodePudding user response:

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.

  • Related