Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create php DateTime object from unix timestamp, set timezone in one line

Tags:

php

datetime

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?

like image 869
GrantD71 Avatar asked Nov 11 '16 19:11

GrantD71


People also ask

How to change timezone in DateTime PHP?

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!

How can I change Unix timestamp to date in PHP?

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.

How can I timestamp in PHP?

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.


2 Answers

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

like image 194
vascowhite Avatar answered Oct 17 '22 17:10

vascowhite


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.

like image 44
raphael75 Avatar answered Oct 17 '22 15:10

raphael75