4

I'm using predefined Phone Formats to format a national phone number but returned the national significant number. not prefixed with 0. for example:

US Phone#

PhoneNumber = +16175551212   (national number is 6175551212)
pf = new PhoneFormat("(XXX) XX XXXXX", dialingCodeUS);
PhoneNumberUtil.formatByPattern(PhoneNumber, PhoneNumberFormat.NATIONAL, pf)
result: (617) 55 51212      GOOD!

IL (Israel) Phone#

PhoneNumber = +972545551212   (national number is 0545551212)
pf = new PhoneFormat("XXX-XXX XXXX", dialingCodeUS);
PhoneNumberUtil.formatByPattern(PhoneNumber, PhoneNumberFormat.NATIONAL, pf)

result: 545551212        BAD!

Expected it to be: 054-555 1212

I cannot do it using other method just because this method (formatByPattern) accept predefined PhoneFormats

from javadoc: PhoneNumberUtil.formatByPattern

public String formatByPattern(Phonenumber.PhoneNumber number,
                     PhoneNumberUtil.PhoneNumberFormat numberFormat,
                     List<Phonemetadata.NumberFormat> userDefinedFormats)

Formats a phone number in the specified format using client-defined formatting rules. Note that if the phone number has a country calling code of zero or an otherwise invalid country calling code, we cannot work out things like whether there should be a national prefix applied, or how to format extensions, so we return the national significant number with no formatting applied. Parameters: number - the phone number to be formatted numberFormat - the format the phone number should be formatted into userDefinedFormats - formatting rules specified by clients Returns: the formatted phone number

Demo: https://libphonenumber.appspot.com/

So my current issue is to find an approach to add this leading zero in an elegant way.

It there a way to format the number using predefined Phone formats and yet having the leading zero as expected?

roeygol
  • 4,908
  • 9
  • 51
  • 88

1 Answers1

0

Is your intention absolutely to omit the dash symbol towards the end of the number? Otherwise, my take on it (having never used this package) was to do the following in order to display the Israeli number in national fashion:

    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

    String pn ="+972545551212";

    Phonenumber.PhoneNumber number = null;
    try {
        number = phoneUtil.parse(pn, "IL");
        System.out.println(phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.NATIONAL));
    } catch (NumberParseException e) {
        e.printStackTrace();
    }

This yields:

054-555-1212
RBH
  • 261
  • 1
  • 10