Create DateTime From Unix Timestamp in PHP 8.4

Create DateTime From Unix Timestamp in PHP 8.4

Working with dates and times is a fundamental aspect of many PHP applications, whether you're dealing with logging, scheduling, or displaying formatted dates. The DateTime class in PHP provides robust functionality to simplify these tasks, offering a flexible and powerful way to handle date and time operations efficiently.

In versions prior to PHP 8.4, we can create DateTime or DateTimeImmutable instance from a Unix timestamp by using the createFromFormat method with the U or U.u formats, or by passing the @TIMESTAMP_VALUE parameter to the constructor.

<?php

echo DateTime::createFromFormat('U', '1732721000')->format('Y-m-d h:i:s').PHP_EOL;
echo DateTime::createFromFormat('U.u', '1732721000.136')->format('Y-m-d h:i:s.u').PHP_EOL;
echo (new DateTime('@1732721000'))->format('Y-m-d h:i:s').PHP_EOL;

Output:

2024-11-27 03:23:20
2024-11-27 03:23:20.136000
2024-11-27 03:23:20

Since PHP 8.4, the createFromTimestamp method can be used to create a DateTime or DateTimeImmutable instance from a Unix timestamp, supporting both standard timestamps and those with microseconds.

<?php

echo DateTime::createFromTimeStamp(1732721000)->format('Y-m-d h:i:s').PHP_EOL;
echo DateTime::createFromTimeStamp(1732721000.136)->format('Y-m-d h:i:s.u').PHP_EOL;

Leave a Comment

Cancel reply

Your email address will not be published.