Convert UTC date&time to Europe/Lisbon

Viewed 139

I want to convert date UTC for Europe/Lisbon, but the code I have gives me different outputs/times:

$datafull = "13-04-2021 08:47:13";

$date = new DateTime($datafull);
$date->setTimezone(new DateTimeZone('Europe/Lisbon')); 
echo $date->format('d-m-Y H:i:s (e)'); 
// 13-04-2021 09:47:13 (Europe/Lisbon)

$datetime = new DateTime($datafull, new DateTimeZone('Europe/Lisbon'));
print $datetime->format('d-m-Y H:i:s (e)');
// 13-04-2021 08:47:13 (Europe/Lisbon)
1 Answers

When you supply a timezone object to the DateTime constructor you're telling it in what timezone the give $datafull is. So in:

$datetime = new DateTime($datafull, new DateTimeZone('Europe/Lisbon'));

You say it is in Europe/Lisbon, and it stays there.

In the other code:

$date = new DateTime($datafull);
$date->setTimezone(new DateTimeZone('Europe/Lisbon')); 

The default timezone is used when the DateTime is constructed, probably UTC on your server, and then you change it afterwards on the second line to Europe/Lisbon, which is an hour ahead.

See: DateTime::__construct

Related