Created
April 24, 2018 03:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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