您的位置:首页 > 其它

学习总结之 时间数字格式化

2014-06-05 00:15 579 查看

一Date Format

1.1 SimpleDateFormat

// hh小写为12小时制;注意大小写有影响的!!
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sd.format(new Date());
/** 2014-06-02 09:52:59 **/

1.2 DateFormat

/**
* // 日期时间格式
DateFormat.FULL;
DateFormat.LONG;
DateFormat.MEDIUM;
DateFormat.SHORT;

日期类型:
FULL 2014年6月1日星期日
LONG 2014年6月1日
MEDIUM 2014-6-1
SHORT 14-6-1
时间
FULL 上午09时56分10秒
CST
LONG 上午09时56分27秒
MEDIUM 9:56:42
SHORT 上午9:56
*/

public
void
test1() throws Exception {
String str = "2014-6-1
上午09时56分27秒";
// 确定是那种地区的时间显示
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,
DateFormat.MEDIUM, Locale.CHINA);
// 转化为Date类型
Date date = df.parse(str);
System.out.println(date);
// 把时间格式化
String date1 = df.format(new Date());
System.out.println(date1);
}

二 Number Format

2.1 Number/Currency/tPercent

@Test
public
void
test1() throws Exception {
NumberFormat nf1 = NumberFormat.getNumberInstance(Locale.US);
System.out.println(nf1.format(10000));
/** 10,000 **/

NumberFormat nf2 = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf2.format(10000));
/** $10,000.00 **/

NumberFormat nf3 = NumberFormat.getPercentInstance(Locale.US);
System.out.println(nf3.format(0.2));
/** 20% **/
}

2.2 Example

//1.3 国际化多个数据
public
void
format_message() throws ParseException {
// 格式化: 日期,中文;
金额,显示中文
String str = "on {0}, a hurricance destroyed 99 houses and caused {1} of damage";
String s1 = "Jul 3, 1998 12:30 PM";
String s2 = "$1000000";

//s1 转换Date
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, Locale.US);
Date s1_date = df.parse(s1);

//s2转换为数字
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
Number s2_num = nf.parse(s2);

// 国际化信息(多个内容)
MessageFormat mf = new MessageFormat(str);

// 占位符对应的值
Object[] obj = {
DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL, Locale.CHINA).format(s1_date),
NumberFormat.getCurrencyInstance(Locale.CHINA).format(s2_num)
};

// 对多个内容进行国际化
String result_str = mf.format(obj);
// 国际化的字符串
System.out.println(result_str);
}

三 国际化

3.1 ResourceBundle

<%
// 获取语言环境对象
Locale locale = request.getLocale();
// 加载资源包
ResourceBundle bunble = ResourceBundle.getBundle("msg",locale);
%>
<title><%=bunble.getString("title")%></title>

3.2 JSTL国际化

<!-- 1. 设置语言环境 -->
<fmt:setLocalevalue="${pageContext.request.locale}"/>
<!-- 2. 加载资源包: basename,属性文件文件名,需要带上包名
-->
<fmt:setBundlebasename="cn/itcast/fmt/msg"var="b"/>

<title><fmt:messagebundle="${b}"
key="title"></fmt:message></title>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: