Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4
Published on by Paul Redmond
Creating a DateTime
from a Unix timestamp will be more convenient in PHP 8.4 with the new createFromTimestamp()
method. It will support both a typical Unix timestamp as well as timestamps containing microseconds:
$dt = DateTimeImmutable::createFromTimestamp(1718337072);$dt->format('Y-m-d'); // 2024-06-14 $dt = DateTimeImmutable::createFromTimestamp(1718337072.432);$dt->format('Y-m-d h:i:s.u'); // 2024-06-14 03:51:12.432000
With PHP 8.3 and below, you need to use the createFromFormat()
method to convert a timestamp into a DateTime
or DateTimeImmutable
instance. As you can see below, it's not too complicated, but it'll be nice to have a new method to take care of both cases below:
$dt = DateTimeImmutable::createFromFormat('U', (string) 1718337072);// DateTimeImmutable @1718337072 {#7948// date: 2024-06-14 03:51:12.0 +00:00,// } $dt = DateTimeImmutable::createFromFormat('U.u', (string) 1718337072.432);// DateTimeImmutable @1718337072 {#7950// date: 2024-06-14 03:51:12.432 +00:00,// }
For those using the Carbon PHP library, it already has a createFromTimestamp()
method available! It is encouraging that PHP is getting this new method at the language level as well!
Carbon\Carbon::createFromTimestamp(1718337072.432);// Carbon\Carbon @1718337072 {#7981// date: 2024-06-14 03:51:12.432 UTC (+00:00),// } Carbon\CarbonImmutable::createFromTimestamp(1718337072);// Carbon\CarbonImmutable @1718337072 {#7999// date: 2024-06-14 03:51:12.0 UTC (+00:00),// }