Skip to content

Instantly share code, notes, and snippets.

@aliihsansepar
Created February 25, 2025 10:35
Show Gist options
  • Save aliihsansepar/c1b20fe59e6849641fe45e9adfc47643 to your computer and use it in GitHub Desktop.
Save aliihsansepar/c1b20fe59e6849641fe45e9adfc47643 to your computer and use it in GitHub Desktop.
Laravel Timezone Service
<?php
namespace Kolay\Time\Services\TimeZone;
use DateTimeZone;
class TimeZoneService
{
/**
* Get all available timezones with their offsets
*
* @return array<string, array>
*/
public function getTimezones(): array
{
$timezones = [];
$identifiers = DateTimeZone::listIdentifiers();
foreach ($identifiers as $identifier) {
$timezone = new DateTimeZone($identifier);
$offset = $timezone->getOffset(now());
$offsetString = $this->formatOffset($offset);
// Group by region
$region = explode('/', $identifier)[0];
$timezones[$region][] = [
'id' => $identifier,
'name' => str_replace('_', ' ', $identifier),
'offset' => $offsetString,
'display' => "({$offsetString}) ".str_replace('_', ' ', $identifier),
];
}
// Sort regions
ksort($timezones);
// Sort timezones within each region
foreach ($timezones as &$regionTimezones) {
usort($regionTimezones, function ($a, $b) {
return $a['name'] <=> $b['name'];
});
}
return $timezones;
}
/**
* Format timezone offset
*/
private function formatOffset(int $offset): string
{
$hours = abs($offset) / 3600;
$minutes = abs($offset) % 3600 / 60;
return sprintf('%s%02d:%02d',
$offset < 0 ? '-' : '+',
floor($hours),
$minutes
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment