9

I know that in php you can create an DateTime object from a unix timestamp and set its timezone in multiple lines like the following:

$date = new DateTime('@' . $timestamp);
$date_with_timezone = $date->setTimezone(new DateTimeZone('America/Chicago'));

I would like to do this on one line however. The following does not work:

$date_with_timezone = new DateTime('@' . $timestamp, new DateTimeZone('America/Chicago'));

Is there any way to create a php DateTime object from a unix timestamp, and set a timezone on the same line?

GrantD71
  • 1,787
  • 3
  • 19
  • 27

3 Answers3

14

Class member access on instantiation (e.g. (new foo)->bar()) support was introduced in PHP version 5.4 (see the release notes), so you can do this:-

$date = (new DateTime('@' . $timestamp))->setTimezone(new DateTimeZone('America/Chicago'));

See it working

vascowhite
  • 18,120
  • 9
  • 61
  • 77
3

There is a note on the timezone documentation:
Note:

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

http://php.net/manual/en/datetime.construct.php

As a workaround, you could probably create a function and pass in the timestamp and time zone. Then you could accomplish the goal of keeping the variable assignment on the same line. In the function, you could create the DateTime object using the timestamp, then assign the timezone and return it.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
raphael75
  • 2,982
  • 4
  • 29
  • 44
0

I correct my response, it is really possible in one line ...

$time_stamp = 1671231344;
$Date_Object = ( new DateTime('now',new DateTimeZone('Europe/Paris')) )
->setTimestamp($time_stamp)
->format('d/m/Y H:i');
        
        // test : 
        echo $Date_Object;

Test :

16/12/2022 23:55