I'm using Google's libphonenumber library to validate and format a phone number in a Java application.
Below is the code I'm using:
String phoneNumberE164Format = "3365440901";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, "US");
phoneNumberE164Format = phoneUtil.formatByPattern(phoneNumberProto,
PhoneNumberFormat.INTERNATIONAL, ******);
The method signature is as such:
public java.lang.String formatByPattern(PhoneNumber number,
PhoneNumberUtil.PhoneNumberFormat numberFormat,
java.util.List<NumberFormat> userDefinedFormats);
Now I don't understand what should be entered for the third parameter.
I would want the format to be like below:
+1.410.218.9999 OR
+1-210-125-9999
Milind Gokhale's comment above gave me a good lead to finding the solution.
The code below formats any valid phone number to the format specified in this question:
NumberFormat newNumFormat = new NumberFormat();
newNumFormat.pattern = "(\\d{3})(\\d{3})(\\d{4})";
newNumFormat.format = "$1-$2-$3";
List<NumberFormat> newNumberFormats = new ArrayList<NumberFormat>();
newNumberFormats.add(newNumFormat);
String formatted = phoneUtil.format(phoneNumberProto, PhoneNumberFormat.RFC3966).substring(4);
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