How to change phone number layout with Java

H

Each country has its own phone number format. But what if you want a universal layout for all types of phone numbers? You can use Libphonenumber. With Libphonenumber, you can change phone layouts, create your own layouts, cast layouts and many more!

Maven:

<dependency>
    <groupId>com.googlecode.libphonenumber</groupId>
    <artifactId>libphonenumber</artifactId>
    <version>3.1</version>
</dependency>

As example, we take a phone number:

String swissNumberStr = "0446681800";

We will change that layout to a Swiss layout:

PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");

Full code:

String swissNumberStr = "0446681800";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

You can also choose other layouts:

// Produces "+41 44 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));
// Produces "044 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));
// Produces "+41446681800"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));

You can change the layout to other country layouts:

System.out.println(phoneUtil.formatOutOfCountryCallingNumber(swissNumberProto, "US"));

Libphonenumber gives you the opportunity to create your own layout:

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
System.out.println(formatter.inputDigit('6')); // Outputs "6"
System.out.println(formatter.inputDigit('5')); // Outputs "65"
System.out.println(formatter.inputDigit('0')); // Outputs "650"
System.out.println(formatter.inputDigit('2')); // Outputs "650 2"
System.out.println(formatter.inputDigit('5')); // Outputs "650 25"
System.out.println(formatter.inputDigit('3')); // Now outputs "650 253"

You can get a phone number layout by using Locale:

PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();
// Output "Engels"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ENGLISH);
// Output "Duits"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.GERMAN);
// Output "Italiaans"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ITALIAN);

For more information: http://code.google.com/p/libphonenumber/

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud

Categories