2013-03-12 138 views
5

我想從字符串轉換爲LOCALDATE的(約達時間),但它給我的錯誤字符串到本地日期錯誤

String theDate = w.getPSDate(); == 6/03/2013 
LocalDate ld = new LocalDate(theDate); 
System.out.println(ld); 

出於某種原因,我不得不使用字符串,而不是最新的。我想打印日期(2013年3月6日)。代碼中的錯誤是什麼?

錯誤

Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "06/03/2013" is malformed at "/03/2013" 
at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:747) 
at org.joda.time.convert.StringConverter.getPartialValues(StringConverter.java:87) 
at org.joda.time.LocalDate.<init>(LocalDate.java:406) 
at org.joda.time.LocalDate.<init>(LocalDate.java:354) 
at Date.GetDate.main(GetDate.java:94) 

Java結果:1

回答

7

使用DateTimeFormatter代替:

// Are you sure it's 6/03/2013 rather than 06/03/2013? dd would be nicer... 
DateTimeFormatter formatter = DateTimeFormat.forPattern("d/MM/yyyy"); 
LocalDate date = formatter.parseLocalDate(text); 
+0

如果我打印日期它出來爲2013年3月6日,而不是06/03/2013。它是06/03/2013。 – vijay 2013-03-12 10:15:47

+0

@vijay:您的問題是關於將*從* String轉換爲* LocalDate。要在另一個方向上轉換,可以使用相同的格式化程序及其「print」方法。 – 2013-03-12 10:31:37