Creating a date object from a timestamp with PHP

Published on 2024-02-27 • Modified on 2024-02-27

This snippet shows three ways to create a date object from a timestamp with PHP. The trick with the @ prefix is not well known. Note that in the first case, the timezone is set to UTC unlike, the two other ways.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Carbon\Carbon;
use Symfony\Component\HttpFoundation\Request;

/**
 * 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 Snippet294Trait
{
    public function snippet294(Request $request): void
    {
        $timestamp = 1709017882; // 2024-02-27 7h11

        $date = (new \DateTime())
            ->setTimestamp($timestamp)
            // ->setTimezone(new \DateTimeZone('Europe/Paris'))
        ;
        var_dump($date, $date->format(\DateTimeInterface::ATOM));
        echo PHP_EOL;

        $date2 = new \DateTime('@'.$timestamp);
        var_dump($date2, $date2->format(\DateTimeInterface::ATOM));
        echo PHP_EOL;

        /** @var \DateTimeImmutable $date3 */
        $date3 = \DateTimeImmutable::createFromFormat('U', (string) $timestamp);
        var_dump($date3, $date3->format(\DateTimeInterface::ATOM));
        echo PHP_EOL;

        // With Carbon
        $date4 = Carbon::createFromTimestamp($timestamp);
        var_dump($date4, $date4->format(\DateTimeInterface::ATOM));
        echo PHP_EOL;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!