Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a phone numbers with libphonenumber in International format.

In the documentation provided by libphonenumber on Github, there is a demo, which converts any provided number into International Format, e.g +4915213116250 is converted into +49 1521 3116250

I want to use the same functionality in C#.

In the documentation of libphone, there is need to parse the number and provide the countries/regions. But the demo works without providing the region/country. Can some body let me know how it is done?

like image 392
Kamran Avatar asked Jul 24 '15 13:07

Kamran


2 Answers

Have you tried this?

var phoneUtil = PhoneNumberUtil.GetInstance();
var numberProto = phoneUtil.Parse("1234567890", "IT");
var formattedPhone = phoneUtil.Format(numberProto, PhoneNumberFormat.INTERNATIONAL);

This will give you "+39 123 456 7890"

like image 161
danyolgiax Avatar answered Sep 22 '22 15:09

danyolgiax


@danyolgiax almost had it. Here's what you do:

var phoneUtil = PhoneNumberUtil.GetInstance();
var numberProto = phoneUtil.Parse("+4915213116250", "ZZ"); //why ZZ means international i don't know
var formattedPhone = phoneUtil.Format(numberProto, PhoneNumberFormat.INTERNATIONAL);

Remember to use phoneUtil.IsValidNumber if you aren't certain that the phone number is valid. Also be aware that phoneUtil.Parse may throw.

like image 20
Chris Jensen Avatar answered Sep 25 '22 15:09

Chris Jensen