我正在使用预定义的电话格式来格式化国内电话号码,但返回了国内有效号码。不以 0 为前缀。
例如:
美国电话#
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(以色列)电话#
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
我不能使用其他方法来做到这一点,因为这种方法 (formatByPattern) 接受预定义的 PhoneFormats
来自 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
演示:https://libphonenumber.appspot.com/
所以我目前的问题是找到一种方法来添加这个前导零
优雅的方式。
有没有一种方法可以使用预定义的电话格式来格式化数字,但仍按预期具有前导零?
最佳答案
您是否绝对打算省略数字末尾的破折号?否则,我对它的看法(从未使用过这个包)是为了以国家方式显示以色列号码:
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();
}
这产生:
054-555-1212
关于java - 如何将前导零添加到国家号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186360/