Skip to content

Commit b166e33

Browse files
committed
[Intl] Add timezone offset utilities
1 parent 73d303a commit b166e33

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/Symfony/Component/Intl/Tests/TimezonesTest.php

+14
Original file line numberDiff line numberDiff line change
@@ -529,4 +529,18 @@ public function testExists()
529529
$this->assertTrue(Timezones::exists('Europe/Amsterdam'));
530530
$this->assertFalse(Timezones::exists('Etc/Unknown'));
531531
}
532+
533+
public function testGetRawOffset()
534+
{
535+
$this->assertSame(0, Timezones::getRawOffset('Etc/UTC'));
536+
$this->assertSame(-10800, Timezones::getRawOffset('America/Buenos_Aires'));
537+
$this->assertSame(20700, Timezones::getRawOffset('Asia/Katmandu'));
538+
}
539+
540+
public function testGetGmtOffset()
541+
{
542+
$this->assertSame('GMT+00:00', Timezones::getGmtOffset('Etc/UTC'));
543+
$this->assertSame('GMT-03:00', Timezones::getGmtOffset('America/Buenos_Aires'));
544+
$this->assertSame('GMT+05:45', Timezones::getGmtOffset('Asia/Katmandu'));
545+
}
532546
}

src/Symfony/Component/Intl/Timezones.php

+24
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace Symfony\Component\Intl;
1313

1414
use Symfony\Component\Intl\Exception\MissingResourceException;
15+
use Symfony\Component\Intl\Exception\RuntimeException;
1516

1617
/**
1718
* Gives access to timezone-related ICU data.
@@ -52,6 +53,29 @@ public static function getNames(string $displayLocale = null): array
5253
return self::asort(self::readEntry(['Names'], $displayLocale), $displayLocale);
5354
}
5455

56+
public static function getRawOffset(string $timezone, int $timestamp = null): int
57+
{
58+
if (null === $timestamp) {
59+
$timestamp = time();
60+
}
61+
62+
$transitions = (new \DateTimeZone($timezone))->getTransitions($timestamp, $timestamp);
63+
64+
if (!isset($transitions[0]['offset'])) {
65+
throw new RuntimeException('No timezone transitions available.');
66+
}
67+
68+
return $transitions[0]['offset'];
69+
}
70+
71+
public static function getGmtOffset(string $timezone, int $timestamp = null): string
72+
{
73+
$offset = self::getRawOffset($timezone, $timestamp);
74+
$abs = abs($offset);
75+
76+
return sprintf('GMT%s%02d:%02d', 0 <= $offset ? '+' : '-', $abs / 3600, $abs / 60 % 60);
77+
}
78+
5579
protected static function getPath(): string
5680
{
5781
return Intl::getDataDirectory().'/'.Intl::TIMEZONE_DIR;

0 commit comments

Comments
 (0)