Basj
Basj

Reputation: 46543

Parse a UTC date, output local datetime

I have already read How to get local time in php? and similar questions, but here I want to do the contrary:

With a given datetime in UTC (e.g. 2021-03-31 23:45:00), how to output the date in local timezone?

$dt = new DateTime("2021-03-31 23:45:00");  // parse the UTC datetime
echo $dt->format('m/d/Y, H:i:s');           

In Europe/Paris timezone, it should output 2021-04-01 01:45:00, but here it sill outputs 2021-03-31 23:45:00. How to fix this?

I also tried with strtotime with a similar result; I also tried with:

date_default_timezone_set('UTC');
$dt = new DateTime("2021-03-31 23:46:14");
date_default_timezone_set('Europe/Paris');
echo $dt->format('m/d/Y, H:i:s');

without success.

Upvotes: 0

Views: 653

Answers (2)

jspit
jspit

Reputation: 7703

This can also be easily solved with date and strtotime:

//The following line is only required if the server has a different time zone.
//date_default_timezone_set('Europe/Paris');

$utcDate = "2021-03-31 23:45:00";

echo date('m/d/Y, H:i:s',strtotime($utcDate.' UTC'));

Output:

04/01/2021, 01:45:00

Upvotes: 1

Syscall
Syscall

Reputation: 19764

You need to change the timezone of the date (using DateTime::setTimeZone()), not the default timezone:

date_default_timezone_set('UTC');
$dt = new DateTime("2021-03-31 23:46:14");
$dt->setTimeZone(new DateTimeZone("Europe/paris")); // change date timezone
echo $dt->format('m/d/Y, H:i:s');

Output:

04/01/2021, 01:46:14

Changing the default timezone affects the new DateTime(), not the format() result.

Upvotes: 1

Related Questions