Java中如何将String转成Date

Java中如何将String转成Date

最近在开发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对象的主流方法,希望对大家有所帮助。

上一篇:A1130. Infix Expression


下一篇:PAT 甲级 1130 Infix Expression