主要涉及到数字、货币、百分比和日期
例如:
中文:1987-09-19 ¥1000
英文: Sep/09 1987 $100
1) 货币
// 国际化 - 动态文本 - 1. 国际化货币
@Test
public void testI18NCurrency(){
// 模拟语言环境
Locale locale = Locale.CHINA;
double number = 100;
// 工具类
NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
// 国际化货币
String str = nf.format(number);
System.out.println(str);
}
输出:¥100.00
Locale.CHINA改为Locale.US;
输出:$100.00
//面试题: 代码计算: $100 * 10
@Test
public void testCurrency() throws ParseException{
String str = "$100";
int num = 10;
// 1. 分析str值是哪一国家的货币
Locale locale = Locale.US;
// 2. 国际化工具类
NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
// 3. 解析str
Number number = nf.parse(str);
//4.进行计算
int value = number.intValue() * num;
//5.格式化输出
str = nf.format(value);
System.out.println(str);
}
输出:$1,000.00
2) 数值
// 国际化 - 动态文本 - 2. 国际化数值
@Test
public void testI18NNumber(){
Locale locale = Locale.CHINA;
NumberFormat nf = NumberFormat.getNumberInstance(locale);
String str = nf.format(1000000000);
System.out.println(str);
Locale localeUS = Locale.US;
NumberFormat nfUS = NumberFormat.getNumberInstance(localeUS);
String strUS = nfUS.format(1000000000);
System.out.println(strUS);
}
输出:
1,000,000,000
1,000,000,000
3) 百分比
// 国际化 - 动态文本 - 3. 国际化百分比
@Test
public void testI18NPercent(){
Locale locale = Locale.CHINA;
NumberFormat nf = NumberFormat.getPercentInstance(locale);
String str = nf.format(0.325);
System.out.println(str);
Locale localeUS = Locale.US;
NumberFormat nfUS = NumberFormat.getPercentInstance(localeUS);
String strUS = nfUS.format(0.325);
System.out.println(strUS);
}
输出:
32%
32%
4) 日期
// 国际化 - 动态文本 - 4. 国际化日期
/*
* 日期
* FULL 2015年3月4日 星期三
* LONG 2015年3月4日
* FULL 2015年3月4日 星期三
* MEDIUM 2015-3-4
* SHORT 15-3-4
*
* 时间
* FULL 下午04时31分59秒 CST
* LONG 下午04时32分37秒
* MEDIUM 16:33:00
* SHORT 下午4:33
*
*
*/
@Test
public void testI18NDate(){
int dateStyle = DateFormat.FULL;
int timeStyle = DateFormat.FULL;
Locale locale = Locale.CHINA;
DateFormat df = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
String date = df.format(new Date());
System.out.println(date);
Locale localeUS = Locale.US;
DateFormat dfUS = DateFormat.getDateTimeInstance(dateStyle, timeStyle, localeUS);
String dateUS = dfUS.format(new Date());
System.out.println(dateUS);
}
输出:
2017年5月4日 星期四 下午06时16分58秒 CST
Thursday, May 4, 2017 6:17:00 PM CST
// 面试2: 请将时间值:09-11-28 上午10时25分39秒 CST,反向解析成一个date对象。
@Test
public void testDate() throws ParseException{
String str = "09-11-28 上午10时25分39秒 CST";
int dateStyle = DateFormat.SHORT;
int timeStyle = DateFormat.FULL;
Locale locale = Locale.CHINA;
// 创建DateFormat工具类,国际化日期
DateFormat df = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
Date date = df.parse(str);
System.out.println(date);
}
输出:
Sat Nov 28 10:25:39 CST 2009