简体   繁体   中英

PHP Timezone Name to Offset

How would I go about converting a timezone name ("Asia/Dubai", "Europe/Andorra", etc) to a GMT offset in hours (or even seconds, since I can convert it from there).

Most people ask for the reverse, but I need to get a timezone offset from the timezone name provided by GeoNames.

you can use the following

<?php

$timezone = 'Pacific/Nauru';
$time = new \DateTime('now', new DateTimeZone($timezone));
$timezoneOffset = $time->format('P');
?>

Another option would be to use the available DateTimeZone::getOffset() method, which returns the offset in seconds for the time zone at the specified date/time.

$timezone = new DateTimeZone("Europe/Andorra");
$offset   = $timezone->getOffset(new DateTime);

我喜欢使用PHP Carbon

$offset = Carbon::now('Europe/Andorra')->offsetHours;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM