3

Hello I have a phone number in it's E164 format : +212640588740 and I want to convert it to it's international format : +212 640-588740. There is this library http://code.google.com/p/libphonenumber/ that do this conversion very well but it requires a phone number and a country code witch I can't provide because I'm reading the phone to convert from DB.

Basically I want a script or library that takes the E164 as arguments and turns it into it's international standard format, like the following:

+212640588740 => +212 640-588740
+33336578668 => +33 3 36 57 86 68
+17877491410 => +1 787-749-1410

Any Ideas are welcome, Thank you in Advance.

OussamaLord
  • 1,073
  • 5
  • 28
  • 39
  • 2
    why have you tagged this jquery? are you using jquery and do not mind a solution that uses jquery? – tgkprog May 25 '13 at 11:03
  • 3
    How can you convert a phone number to international format if you don't know the country code? Any solutions without using country code will bring you some issue, earlier or later. Basically, you should add a field in DB to specify for each number the country code. – A. Wolff May 25 '13 at 11:07
  • 1
    can't you extract the country code from your phonenumber? you would need some sort of database with all the country codes and then you take the first numbers of your phone number that match with one of the codes in the database. – basilikum May 25 '13 at 11:24
  • 1
    Here for instance you can find such a list: https://gist.github.com/Goles/3196253 – basilikum May 25 '13 at 11:34
  • Hi, Thanks for the answers but if this is impossible without knowing the country code, How is it working on this link? [link](http://www.phoneformat.com/) Just type the phone number as :+212610478521 and you will see in live the formatting taking effect, so how is it possible? – OussamaLord May 25 '13 at 15:49

1 Answers1

2

If all your input is E164 formatted, you can use com.google.i18n.phonenumbers.PhoneNumberUtil.parse() method to convert your string to PhoneNumber instance which in turn you could use com.google.i18n.phonenumbers.PhoneNumberUtil.format() to convert it to a string formatted as INTERNATIONAL.

You don't need to know the country code (or parse it) beforehand, see the params documentation of the parse() method:

defaultRegion - ... If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.

Here's a short example:

PhoneNumber number = com.google.i18n.phonenumbers.PhoneNumberUtil.parse("+12781112222", null);
String result = com.google.i18n.phonenumbers.PhoneNumberUtil.format(number, com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);

For usage see the docs:

com.google.i18n.phonenumbers.PhoneNumberUtil.parse() com.google.i18n.phonenumbers.PhoneNumberUtil.format()

Sagi Iltus
  • 1,130
  • 10
  • 21