SimpleDateFormat是一个很常用的API,为了给用户更好的用户体验,我们往往需要把时间转化为用户所乐意接受的格式。有些用户需要很简单的日期格式,只需要年月日就行,但有些用户可能比较挑剔,他们需要程序员为他们提供年月日时分秒,甚至星期几。
下面是在网上找到的一张关于SimpleDateFormat的参数说明表:
字母
|
日期或时间元素
|
表示
|
示例
|
G
|
Era
标志符
|
Text
|
AD
|
y
|
年
|
Year
|
1996
;
96
|
M
|
年中的月份
|
Month
|
July
;
Jul
;
07
|
w
|
年中的周数
|
Number
|
27
|
W
|
月份中的周数
|
Number
|
2
|
D
|
年中的天数
|
Number
|
189
|
d
|
月份中的天数
|
Number
|
10
|
F
|
月份中的星期
|
Number
|
2
|
E
|
星期中的天数
|
Text
|
Tuesday
;
Tue
|
a
|
Am/pm
标记
|
Text
|
PM
|
H
|
一天中的小时数(0-23)
|
Number
|
0
|
k
|
一天中的小时数(1-24)
|
Number
|
24
|
K
|
am/pm
中的小时数(0-11)
|
Number
|
0
|
h
|
am/pm
中的小时数(1-12)
|
Number
|
12
|
m
|
小时中的分钟数
|
Number
|
30
|
s
|
分钟中的秒数
|
Number
|
55
|
S
|
毫秒数
|
Number
|
978
|
z
|
时区
|
General time zone
|
Pacific Standard Time
;
PST
;
GMT-08:00
|
Z
|
时区
|
RFC 822 time zone
|
-0800
|
下面是两个输出两种Format的Java Application实现。
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestTimeFormat {
/**
* 返回时间格式为 yyyy-mm-dd hh:mm:ss 的函数
*
*/
public String getYYMMDDHHMMSSDate(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
if(date!=null){
return sdf.format(date);
}else{
return null;
}
}
/**
* 返回时间格式为 yy-mm-dd hh:mm:ss E 的函数
*/
public String getYYMMDDHHMMSSEDate(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss E");
if(date!=null){
return sdf.format(date);
}else{
return null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
TestTimeFormat test = new TestTimeFormat();
Date current = new Date();
System.out.println(test.getYYMMDDHHMMSSEDate(current));
}
}