feature #31295 [Intl] Add timezone offset utilities (ro0NL)
This PR was merged into the 4.3-dev branch.
Discussion
----------
[Intl] Add timezone offset utilities
| Q | A
| ------------- | ---
| Branch? | master
| Bug fix? | no
| New feature? | yes
| BC breaks? | no <!-- see https://symfony.com/bc -->
| Deprecations? | no
| Tests pass? | yes (including intl-data group)
| Fixed tickets | #... <!-- #-prefixed issue number(s), if any -->
| License | MIT
| Doc PR | symfony/symfony-docs#... <!-- required for new features -->
Commits
-------
b166e33e29
[Intl] Add timezone offset utilities
This commit is contained in:
commit
ac4b32257c
@ -529,4 +529,18 @@ class TimezonesTest extends ResourceBundleTestCase
|
||||
$this->assertTrue(Timezones::exists('Europe/Amsterdam'));
|
||||
$this->assertFalse(Timezones::exists('Etc/Unknown'));
|
||||
}
|
||||
|
||||
public function testGetRawOffset()
|
||||
{
|
||||
$this->assertSame(0, Timezones::getRawOffset('Etc/UTC'));
|
||||
$this->assertSame(-10800, Timezones::getRawOffset('America/Buenos_Aires'));
|
||||
$this->assertSame(20700, Timezones::getRawOffset('Asia/Katmandu'));
|
||||
}
|
||||
|
||||
public function testGetGmtOffset()
|
||||
{
|
||||
$this->assertSame('GMT+00:00', Timezones::getGmtOffset('Etc/UTC'));
|
||||
$this->assertSame('GMT-03:00', Timezones::getGmtOffset('America/Buenos_Aires'));
|
||||
$this->assertSame('GMT+05:45', Timezones::getGmtOffset('Asia/Katmandu'));
|
||||
}
|
||||
}
|
||||
|
@ -12,6 +12,7 @@
|
||||
namespace Symfony\Component\Intl;
|
||||
|
||||
use Symfony\Component\Intl\Exception\MissingResourceException;
|
||||
use Symfony\Component\Intl\Exception\RuntimeException;
|
||||
|
||||
/**
|
||||
* Gives access to timezone-related ICU data.
|
||||
@ -52,6 +53,29 @@ final class Timezones extends ResourceBundle
|
||||
return self::asort(self::readEntry(['Names'], $displayLocale), $displayLocale);
|
||||
}
|
||||
|
||||
public static function getRawOffset(string $timezone, int $timestamp = null): int
|
||||
{
|
||||
if (null === $timestamp) {
|
||||
$timestamp = time();
|
||||
}
|
||||
|
||||
$transitions = (new \DateTimeZone($timezone))->getTransitions($timestamp, $timestamp);
|
||||
|
||||
if (!isset($transitions[0]['offset'])) {
|
||||
throw new RuntimeException('No timezone transitions available.');
|
||||
}
|
||||
|
||||
return $transitions[0]['offset'];
|
||||
}
|
||||
|
||||
public static function getGmtOffset(string $timezone, int $timestamp = null): string
|
||||
{
|
||||
$offset = self::getRawOffset($timezone, $timestamp);
|
||||
$abs = abs($offset);
|
||||
|
||||
return sprintf('GMT%s%02d:%02d', 0 <= $offset ? '+' : '-', $abs / 3600, $abs / 60 % 60);
|
||||
}
|
||||
|
||||
protected static function getPath(): string
|
||||
{
|
||||
return Intl::getDataDirectory().'/'.Intl::TIMEZONE_DIR;
|
||||
|
Reference in New Issue
Block a user