最近在開發Json數據反序列化為Java對象的時候發現spring mvc 和 Jackson 對Date類型對支持不是特別好,雖然在Java對象序列化為Json數據的過程中提供了便利的注解,但是反序列化卻沒有,於是就引出了下面的問題,我需要手工的將字符串轉換為Date類型的數據,java.text.SimpleDateFormat 為我們提供了這種轉換的基礎設施。如下列出了的格式化模式的簡單定義,如果 ‘M’ 大於等於3位, 月份會顯示為字母,否則是數字. 更詳細的定義請參考 java.text.SimpleDateFormat JavaDoc。
Letter Description Examples
y Year 2015
M Month in year Nov, 11, 7
d Day in month 1-31
E Day name in week Friday, Sunday
a Am/pm marker AM, PM
H Hour in day 0-23
h Hour in am/pm 1-12
m Minute in hour 0-60
s Second in minute 0-60
1. Date = 7-Nov-2015
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Nov-2015";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output
Mon Nov 07 00:00:00 MYT 2015
07-Nov-2015
2. Date = 07/06/2015
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2015";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output
Mon Nov 07 00:00:00 MYT 2015
07/06/2015
3. Date = Nov 7, 2015
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");
String dateInString = "Nov 7, 2015";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output
Mon Nov 07 00:00:00 MYT 2015
Nov 07, 2015
4. Date = Fri, Nov 7 2015
SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
String dateInString = "Fri, Nov 7 2015";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output
Mon Nov 07 00:00:00 MYT 2015
Mon, Nov 07 2015
2. Date and Time Example
1. Date and Time = Friday, Nov 7, 2015 12:10:56 PM
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Nov 7, 2015 12:10:56 PM";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output
Mon Nov 07 12:10:56 MYT 2015
Monday, Nov 07, 2015 12:10:56 PM
總結
本文簡單的總結了將字符串轉換為Java對象的主流方法,希望對大家有所幫助。