2016-07-01 22 views
0

我想解析一個日期將其轉換爲時代。我嘗試了similar question here沒有成功的解決方案:Java上的String java.time.format.DateTimeParseException

String date = "Jun 4 2015";  
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("LLL dd yyyy").withLocale(Locale.ENGLISH); 
LocalDateTime ldt = LocalDateTime.parse(date, formatter); 
System.out.println(date+" "+ldt.toEpochSecond(ZoneOffset.UTC)); 

我也得到Exception in thread "main" java.time.format.DateTimeParseException: Text 'Jun 4 2015' could not be parsed at index 0即使我相當肯定,我的正則表達式。我在這裏錯過了什麼?

編輯:

繼意見,我改變了LocalDateTime到LOCALDATE的,但繼續得到同樣的錯誤:

String date = "Jun 4 2015";  
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH); 
LocalDate ldt = LocalDate.parse(date, formatter); 
+0

http://stackoverflow.com/questions/30518954/datetimeformatter-month-pattern-letter-l-fails – Reimeus

+0

我用「MMM」取代了「LLL」並獲得了相同的結果。 –

+2

使用MMM是不夠的。你在那裏有一個LocalDate,而不是LocalDateTime:根本沒有時間。將其解析爲LocalDate,然後選擇要將其轉換爲LocalDateTime的時間。 –

回答

6
String date = "Jun 4 2015"; 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH); 
    LocalDate ldt = LocalDate.parse(date, formatter); 

解析罰款。不要放置「dd」,因爲它不會解析少於10天。正如@JB Nizet所說的,您需要使用LocalDate而不是LocalDateTime。

+0

請參閱修改。我仍然收到同樣的錯誤。 –

+1

我清理了這個項目,現在它工作了:p –

+0

這麼多小細節......謝謝@JB Nizet和stdunbar –