1 数字格式
NumberFormat 类接受 Locale 参数,静态工厂方法 getNumberInstance、getCurrencyInstance、getPercentInstance 分别返回对数字、货币量、百分比的格式化和解析。
NumberFormat currFmt = NumberFormat.getCurrencyInstance(Locale.CHINA);
double amt = 123456.78;
String result = currFmt.format(amt);//¥123,456.78
2 货币
Currency 类控制被格式器所处理的货币
NumberFormat cnyFmt = NumberFormat.getCurrencyInstance(Locale.US);
cnyFmt.setCurrency(Currency.getInstance("CNY"));
double amt = 123456.78;
String result = currFmt.format(amt);//CNY123,456.78
3 日期和时间
java.time 包 DateTimeFormatter 类
3.1 格式化
format() 方法:Date -> String
FormatStyle style = FormatStyle.SHORT;
//当前Locale
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(style);
//切换Locale
DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(style).withLocale(locale);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(style);
ZonedDateTime appointment = ...;
String formatted = formatter.format(appointment);
3.2 解析
parse() 方法:String -> Date
LocalTime time = LocalTime.parse("9:32 AM",formatter);