How to Change the Time Zone in PHP

» »

Time zones can be a real pain, and that's even without having to switch between them. Here's a quick tutorial on how to convert time zones using the PHP class DateTime.

The date classes in PHP can be really hard to wrap your head around.

We will use two classes for this excercise;

  1. PHP DateTime Class
  2. PHP DateTimeZone Class

Here's how to do it:

$originalTime = '2019-05-10 15:30:05';
$startDate = DateTime::createFromFormat(
    'Y-m-d G:i',
    $originalTime,
    new DateTimeZone('UTC')
);

$newDate = $startDate;
$newDate->setTimeZone(new DateTimeZone('Sweden/Stockholm'));

Now, to show our output, type the following:

echo $newDate->format('Y-m-d H:i:s');