Skip to content

Instantly share code, notes, and snippets.

@shawnlindstrom
Created April 24, 2018 03:29
Show Gist options
  • Save shawnlindstrom/6c539b078dc1fb2e5648e8310a586805 to your computer and use it in GitHub Desktop.
Save shawnlindstrom/6c539b078dc1fb2e5648e8310a586805 to your computer and use it in GitHub Desktop.
A helper to derive timezone from phone numbers using giggsey/libphonenumber-for-php
<?php
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberToTimeZonesMapper;
use libphonenumber\PhoneNumberUtil;
if (!function_exists('phone_to_timezone')) {
/**
* Returns a timezone for a phone number. Note, multiple timezones are
* possible for non-US regions. Only the first timezone is returned.
* Returns 'Etc/Unknown' when the number is invalid/unparseable,
* or if the timezone is not found in the library's mapping.
*
* @param string $number
* @param string $region
* @return string
*/
function phone_to_timezone($number, $region = 'US'): string
{
$phoneNumberUtil = PhoneNumberUtil::getInstance();
try {
$phoneNumber = $phoneNumberUtil->parse($number, $region);
return PhoneNumberToTimeZonesMapper::getInstance()->getTimeZonesForNumber($phoneNumber)[0];
} catch (NumberParseException $e) {
return 'Etc/Unknown'; // Same return value for valid numbers with unknown timezones
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment