1

I know \DateTimeZone::listIdentifiers() returns all timezone identifiers, but how can I retrieve their actual offset from UTC?

3 Answers 3

1

There is method getoffset

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

You can build an associative array mapping timezones and their offset using the getOffset method of DateTime instance.

getOffset returns the difference in seconds of a date evaluated in the time zone of the provided datetime argument (in our example, this is the current time in utc), and the same datetime as evaluated in the local time zone.

$utcNow = new DateTime('now', (new DateTimeZone('UTC')));
$identOffset = array_map(
    function ($ident) use ($utcNow) {
        $localTimeZone = new DateTimeZone($ident);
        $offset = $localTimeZone->getOffset($utcNow);
        return [$ident => $offset] ;
    },
    DateTimeZone::listIdentifiers()
);
$identOffset = array_merge(...$identOffset);
var_dump($identOffset);

Comments

0

If you are using https://carbon.nesbot.com/

// You will get timezone offset as string
Carbon::now('Asia/Kathmandu')->getOffsetString(); // +05:45 

Comments

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.