Creating a UTC timezone date with PHP

Published on 2022-11-10 • Modified on 2022-11-10

This snippet shows how to create a UTC timezone date with PHP. The first thing to know is that if your server already has UTC as the default timezone (date.timezone = UTC in your php.ini file), you will get the correct date. If not, you must explicitly pass the UTC timezone to the DateTime constructor. CET stands for "Central European Time".



namespace App\Controller\Snippet;

 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
trait Snippet230Trait
    public function snippet230(): void
        $dateUtc = new \DateTime('now', new \DateTimeZone('UTC'));
        $dateParis = new \DateTime('now', new \DateTimeZone('Europe/Paris'));

        echo 'UTC datetime: '.$dateUtc->format(\DateTimeInterface::RFC850).PHP_EOL;
        echo 'Paris datetime: '.$dateParis->format(\DateTimeInterface::RFC850);

        // That's it! 😁

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!