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?
It's really simple to convert a DateTime from one time zone to another in PHP. Just create a DateTime object using date & time to be converted as the first parameter and the original time zone as the second parameter. Then change the time zone to the desired one using the setTimezone method. That's all!
To convert a Unix timestamp to a readable date format in PHP, use the native date() function. Pass the format you wish to use as the first argument and the timestamp as the second.
The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With