Java中如何將String轉成Datejava
最近在開發Json數據反序列化爲Java對象的時候發現spring mvc 和 Jackson 對Date類型對支持不是特別好,雖然在Java對象序列化爲Json數據的過程當中提供了便利的註解,可是反序列化卻沒有,因而就引出了下面的問題,我須要手工的將字符串轉換爲Date類型的數據,java.text.SimpleDateFormat 爲咱們提供了這種轉換的基礎設施。以下列出了的格式化模式的簡單定義,若是 ‘M’ 大於等於3位, 月份會顯示爲字母,不然是數字. 更詳細的定義請參考 java.text.SimpleDateFormat JavaDoc。spring
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對象的主流方法,但願對你們有所幫助。mvc