I'm using this bit of code (in Groovy, but it should be pretty clear what it does)
class MobileNumberUtilService {
def getISOCountryCode(rawNumber) {
def phoneNumberUtil = PhoneNumberUtil.getInstance()
def number
try {
number = phoneNumberUtil.findNumbers(rawNumber, null).iterator().next().number()
} catch (NoSuchElementException exception) {
return ''
}
CountryCodeToRegionCodeMap.countryCodeToRegionCodeMap[number.countryCode].first()
}
}
Running mobileNumberUtilService.getISOCountryCode('<internationalized American or Canadian number>')
returns [US, AG, AI, AS, BB, BM, BS, CA, DM, DO, GD, GU, JM, KN, KY, LC, MP, MS, PR, SX, TC, TT, VC, VG, VI]
.
Is there any way to distinguish those, short of some sort of web service lookup?
Canada is situated in North America and comes under the North American Numbering Plan (NANP). Since all NANP countries have the same country code, "1", you may call from the US to Canada by dialing 1 before the desired number.
Telephone numbers in Canada follow the fixed-length Bell System format, consisting of the country code +1, followed by a three-digit area code, a three-digit central office code (or exchange code) and a four-digit station code. This is represented as 1 NPA NXX XXXX, in which the country code is "1".
What are the parts of a Canadian phone number? Phone numbers in Canada consist of 11 digits — the 1-digit country code, a 3-digit area code, a 3-digit central office or exchange code, and a 4-digit subscriber number.
You can't do that (port your number). Even though both Canada and the United states are on the North American Numbering plan and share the same country code, they have distinct area codes (The first 3 digits of the phone number). A provider can only port in a number to an area code that they are licensed to operate in.
Take a look at the geocoder subproject of libphonenumber. It provides a PhoneNumberOfflineGeocoder
that does exactly what you're looking for:
@Grapes([
@Grab('com.googlecode.libphonenumber:libphonenumber:5.8'),
@Grab('com.googlecode.libphonenumber:geocoder:2.9')
])
import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder
def phoneNumberUtil = PhoneNumberUtil.instance
def geocoder = PhoneNumberOfflineGeocoder.instance
def usaNum = phoneNumberUtil.parse("1-406-750-9999", "US")
def canNum = phoneNumberUtil.parse("1-416-750-9999", "US")
assert geocoder.getCountryNameForNumber(usaNum, Locale.default) ==
"United States"
assert geocoder.getCountryNameForNumber(canNum, Locale.default) ==
"Canada"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With