How to convert a Unix timestamp to a DateTime object and vice versa in PHP?

To convert a Unix timestamp to a DateTime object in PHP, you can use the DateTime class and its setTimestamp() method. Here's an example:

$timestamp = 1631312426; // UNIX timestamp $datetime = new DateTime(); $datetime->setTimestamp($timestamp);

To convert a DateTime object to a Unix timestamp, you can use the getTimestamp() method. Here's an example:

$datetime = new DateTime('2021-09-10 12:34:56'); $timestamp = $datetime->getTimestamp();

Note that the DateTime class requires PHP 5.2 or later versions.