raphael75
raphael75

Reputation: 3238

get timezone offset from UNIX timestamp in PHP

In PHP 7.2, if I do this:

<?php
$dt = new DateTime('@1522680410', new DateTimeZone(date_default_timezone_get())); 
$tz_offset = $exp->getOffset();
?>

$tz_offset always returns 0. However, if I set a date and not a UNIX timestamp (i.e., '2018-01-02' instead of '@1522680410') it shows the correct offset value.

Is there a way to have the timestamp return the timezone offset in one step like above?

Upvotes: 1

Views: 948

Answers (2)

Glavić
Glavić

Reputation: 43552

Unix timestamp is always in UTC timezone (or ±00:00 offset). If not, you are doing something nasty :)

If you take a look at DateTime::__construct(), you will see note on 2nd argument:

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).

Change timezone after you have created DateTime object:

$dt = new DateTime('@1522680410');
$dt->setTimezone(new DateTimeZone(date_default_timezone_get())); 

Upvotes: 1

raphael75
raphael75

Reputation: 3238

Apparently you can do it this way:

<?php
$dt = new DateTime(DateTime::createFromFormat('U', '1522680410')->format('Y-m-d'), new DateTimeZone(date_default_timezone_get()));
?>

Upvotes: 0

Related Questions