原文转载自 http://www.cankaojishu.com/bcyy/82141.html
日期、数字格式化显示,是web开发中的常见需求,spring mvc采用XXXFormatter来处理,先看一个最基本的单元测试:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
package
com.cnblogs.yjmyzz.test;
import
java.math.BigDecimal;
import
java.util.Date;
import
java.util.Locale;
import
org.junit.Test;
import
org.springframework.context.i18n.LocaleContextHolder;
import
org.springframework.format.datetime.DateFormatter;
import
org.springframework.format.number.CurrencyFormatter;
import
org.springframework.format.support.DefaultFormattingConversionService;
public
class
FormatterTest {
@Test
public
void
testFormatter() {
//设置上下语言的语言环境
LocaleContextHolder.setLocale(Locale.US);
//--------测试日期格式化----------
Date d =
new
Date();
DateFormatter dateFormatter =
new
DateFormatter();
//按中文格式输出日期
System.out.println(dateFormatter.print(d, Locale.CHINESE));
//2014-10-30
DefaultFormattingConversionService conversionService =
new
DefaultFormattingConversionService();
//添加前面的DateFormatter
conversionService.addFormatter(dateFormatter);
System.out.println(conversionService.convert(d, String.
class
));
//Oct 30, 2014
dateFormatter.setPattern(
"yyyy年MM月dd日"
);
System.out.println(conversionService.convert(d, String.
class
));
//2014年10月30日
// --------测试货币格式化-------------
CurrencyFormatter currencyFormatter =
new
CurrencyFormatter();
BigDecimal money =
new
BigDecimal(
1234567.890
);
System.out.println(currencyFormatter.print(money, Locale.CHINA));
//¥1,234,567.89
conversionService.addFormatter(currencyFormatter);
System.out.println(conversionService.convert(money, String.
class
));
//$1,234,567.89
}
}
|
除了DateFormatter、CurrencyFormatter,常用还有的以下Formatter:
原文转载自 http://www.cankaojishu.com/bcyy/82141.html