php - Output of date() and DateTime::format() differ, DateTime::format() ignores timezone

I've set the timezone of PHP to 'Europe/Berlin' in php.ini, which should be +1 to UTC (in winter).

When I output a Unix timestamp (UTC) to the user (with Apache and browser) by using date(), the timezone is used correctly. When I output the same timestamp with DateTime::format(), there is no timezone applied, until I set it explicitly with DateTime::setTimezone().

See the following example code:

<?php

$now = time();

// Verify Timezone
$tz = ini_get('date.timezone');
echo 'Timezone: ' . $tz  . '<br>';

// Using date
echo 'date(): ' . date('Y-m-d H:i:s', $now) . '<br>';

// Using DateTime
$dt = new DateTime('@' . $now);
echo 'DateTime1: ' . $dt->format('Y-m-d H:i:s') . '<br>';

// Setting DateTime timezone explicitly
$dt->setTimezone(new DateTimeZone('Europe/Berlin'));
echo 'DateTime2: ' . $dt->format('Y-m-d H:i:s') . '<br>';

Output:

Timezone: Europe/Berlin
date(): 2020-12-09 15:31:32
DateTime1: 2020-12-09 14:31:32
DateTime2: 2020-12-09 15:31:32

Why is that? I can't see any hints in the docs that DateTime::format() ignores the timezone set in php.ini by default.

Answer

Solution:

As @El_Vanja pointed out in the comments, the DateTime constuctor ignores the timezone when being set by unix timestamp (see docs)

The ::format() method takes into regard what is set in the object (=UTC) and not what is set in php.ini.

Source