如何使用 PhoneNumberUtils 库将电话号码格式化为没有国家前缀的国家格式?

Posted

技术标签:

【中文标题】如何使用 PhoneNumberUtils 库将电话号码格式化为没有国家前缀的国家格式?【英文标题】:How to format phone number to national format without national prefix using PhoneNumberUtils library? 【发布时间】:2017-01-22 22:57:00 【问题描述】:

我正在尝试将以前 E164 格式的电话号码格式化为没有国家前缀号码的国家格式,我正在使用 PhoneNumberUtils 来做到这一点:

public static String getNationalPhone(String phoneE164Formatted) 
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    String phoneNumber = phoneE164Formatted;
    try 
        Phonenumber.PhoneNumber numberProto = phoneUtil.parseAndKeepRawInput(phoneE164Formatted, "");
        phoneNumber = phoneUtil.format(numberProto, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
     catch (NumberParseException e) 
        e.printStackTrace();
    

    return phoneNumber;

使用该代码,我得到了我不想要的国家前缀。例如,将这个数字“+526143342293”格式化为国家格式给了我这个结果:“01 614 334 22 93”,其中“01”是我想要抑制的。

【问题讨论】:

【参考方案1】:

https://github.com/brick/phonenumber/blob/master/src/PhoneNumber.php

这些答案在php中,你可以转换成你自己的。

public function getCountryCode()

    return (string) $this->phoneNumber->getCountryCode();

转换上述代码将得到所需格式的国家号码。

【讨论】:

以上是关于如何使用 PhoneNumberUtils 库将电话号码格式化为没有国家前缀的国家格式?的主要内容,如果未能解决你的问题,请参考以下文章

PhoneNumberUtils 更改号码格式

使用电话号码格式 NaN 屏蔽 EditText,如 PhoneNumberUtils

PhoneNumberUtils.isGlobalPhoneNumber 无法正常工作

PhoneNumberUtils.formatNumberToE164 不需要的方法结果

如何使用 gson 库将字符串转换为 JsonObject

如何使用 PDFsharp .NET 库将 PDF 页面导出为图像?