19
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaで電話番号フォーマット

Last updated at Posted at 2014-02-20

なんだよーこいつもすげーらくじゃーん

<dependency>
	<groupId>com.googlecode.libphonenumber</groupId>
	<artifactId>libphonenumber</artifactId>
	<version>3.6</version>
</dependency>
String tel = "0451234567";
Phonenumber.PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(tel, "JP");
tel = PHONE_NUMBER_UTIL.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
System.out.println(tel);

045-123-4567

になるぜ。

SpringのCustomEditor使ってこんな風にもねぇ。

public class PhoneNumberEditor extends PropertyEditorSupport {

	private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();

	@Override
	public void setAsText(String text) {
		if (!StringUtils.hasText(text)) {
			setValue(null);
		}
		else {
			try {
				Phonenumber.PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(text, "JP");
				text = PHONE_NUMBER_UTIL.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
			}
			catch (NumberParseException e) {
				// Do Nothing
			}
			setValue(text);
		}
	}
}
@Controller
@RequestMapping(value="/hoge")
public class HogeController {

	@InitBinder(FORM_MODEL_KEY)
	public void initBinder(WebDataBinder binder, HttpServletRequest request) {
		binder.registerCustomEditor(String.class, "tel", new PostalCodeEditor());
	}
	...
}
19
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?