PHP – Setting and Getting Timestamp from DateTime Object below PHP 5.3.x

So we solved the timezone problem using PHP’s timezone aware DateTime class right? And you love working on UNIX timestamp/UTC but as to your surprise, you cannot set or get timestamp to a DateTime object on version below PHP 5.3.x. Worry no more, there are some workarounds.

Setting timestamp

Setting timestamp on PHP version 5.3.x and above can be achieved by using the setTimestamp method of DateTime class. Example below:

$d = new DateTime('now', new DateTimeZone('US/Pacific'));
$d->setTimestamp(1354093404);

For some reason you like it that way but why don’t you just set the timestamp on constructor instead? For demo purposes, we do that since this method is only available on PHP 5.3.x and above. For below 5.3.0, use below technique.

$d = new DateTime('@1354093404');

The @ symbol will tell DateTime to interpret it as timestamp. As usual, ugly PHP design.

Getting timestamp

PHP 5.3.x and above also has the method for getting timestamp for a given DateTime object. See example below:

$d = new DateTime('now', new DateTimeZone('US/Pacific'));
var_dump($d->getTimestamp());

For PHP versions below 5.3.0, use the following technique instead.

$d = new DateTime('now', new DateTimeZone('US/Pacific'));
var_dump($d->format('U'));

The U format will return timestamp format.

That’s it!

This entry was posted in php and tagged , , , . Bookmark the permalink.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *