Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将前导零添加到国家编号?_Java_Formatting_Internationalization_Phone Number_Libphonenumber - Fatal编程技术网

Java 如何将前导零添加到国家编号?

Java 如何将前导零添加到国家编号?,java,formatting,internationalization,phone-number,libphonenumber,Java,Formatting,Internationalization,Phone Number,Libphonenumber,我正在使用预定义的电话格式格式化国家电话号码,但返回了国家有效号码。不以0作为前缀。 例如: 美国电话# IL(以色列)电话# 我不能使用其他方法,因为此方法(formatByPattern)接受预定义的PhoneFormats 从javadoc: 公共字符串formatByPattern(Phonenumber.Phonenumber, PhoneNumberUtil.PhoneNumberFormat numberFormat, 列出用户定义的格式) 使用客户端定义的格式化规则以指定格式

我正在使用预定义的电话格式格式化国家电话号码,但返回了国家有效号码。不以0作为前缀。 例如:

美国电话#

IL(以色列)电话#

我不能使用其他方法,因为此方法(formatByPattern)接受预定义的PhoneFormats

从javadoc:

公共字符串formatByPattern(Phonenumber.Phonenumber,
PhoneNumberUtil.PhoneNumberFormat numberFormat,
列出用户定义的格式)
使用客户端定义的格式化规则以指定格式格式化电话号码。请注意,如果电话号码有国家/地区呼叫 代码为零或其他无效的国家/地区呼叫代码,我们无法 解决诸如是否应该有国家前缀之类的问题 应用,或者如何格式化扩展,所以我们返回 未应用格式的有效数字。参数:编号- 要格式化的电话号码numberFormat-手机的格式 数字应格式化为userDefinedFormats-格式化规则 由客户端指定返回:格式化的电话号码

演示:

因此,我当前的问题是找到一种方法,在 优雅的方式


有没有一种方法可以使用预定义的电话格式来设置号码格式,同时又能像预期的那样保留前导零位?

您是否绝对打算在号码末尾省略破折号符号?否则,我的想法(从未使用过此软件包)是为了以全国性的方式显示以色列的数字:

    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

如果你清楚地说明电话号码的规则,这会有所帮助。也许这些信息隐藏在你的问题中,但它并不是那么明显(至少对我来说不是)。我只是想用一种优雅的方式,使用这个谷歌库将前导号码添加到我的电话号码中,我提到了一个例子,请看一下哪些规则/输入应该和不应该添加前导零?你说的是格式和模式吗?我放弃。你难倒我了。
public String formatByPattern(Phonenumber.PhoneNumber number,
                     PhoneNumberUtil.PhoneNumberFormat numberFormat,
                     List<Phonemetadata.NumberFormat> userDefinedFormats)
    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