1

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?

2 Answers 2

1

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())); 
Sign up to request clarification or add additional context in comments.

Comments

0

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()));
?>

1 Comment

With this solution you lose time part. And you don't need to set timezone to default, since default is already taken (no timezone definition in 1st parameter). Two DateTime object generation is an overkill.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.