2015-07-01 22 views
3

我想分析由月(1-12)和年份的例如像日期:解析與一個月日期沒有前導0

1.2015 
12.2015 

LocalDate

我得到使用此代碼的異常:

final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("M.yyyy"); 
LocalDate monthYearDate = LocalDate.parse(topPerformanceDate, monthYearFormatter); 

java.time.format.DateTimeParseException:文本 '6.2015' 無法解析:無法從TemporalAccessor獲得LOCALDATE:{MonthOfYear = 6,年份= 2015},輸入的ISO java.time.format.Parsed

documentation在短月格式上對我來說不是很清楚。

編輯:我猜這個問題是月份錯過了嗎?

+2

我不是Java專家,但您希望解析日期中的哪一天? – nrodic

+0

我希望這個月的某一天不確定... –

+0

您以後想用這樣一個無聊的約會怎麼樣? – Pshemo

回答

8

由於您的輸入不是一個日期,而是每個月/年的組合,我會建議使用YearMonth類:

String input = "1.2015"; 
YearMonth ym = YearMonth.parse(input, DateTimeFormatter.ofPattern("M.yyyy")); 

在您添加評論您需要本月的第一天和最後一天:

LocalDate firstOfMonth = ym.atDay(1); 
LocalDate endOfMonth = ym.atEndOfMonth(); 
-2

只有兩種情況,你爲什麼不試試它們呢?

final DateTimeFormatter monthYearFormatter1 = DateTimeFormatter.ofPattern("MM.yyyy"); 
final DateTimeFormatter monthYearFormatter2 = DateTimeFormatter.ofPattern("M.yyyy"); 

LocalDate monthYearDate; 
try{ 
    monthYearDate= LocalDate.parse(topPerformanceDate, monthYearFormatter1); 
}catch(DateTimeParseException e){ 
    monthYearDate=LocalDate.parse(topPerformanceDate, monthYearFormatter2); 
} 
+0

兩人都試過,即使是L.yyyy,在所有情況下都得到了例外。 –

+0

@kosmičák嗯好吧,看來你通過增加一天來修復它...奇怪 – nafas

3

看來問題確實是一個月的失蹤日子。我的解決方法是設置它:

final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("d.M.yyyy"); 
    month = LocalDate.parse("1." + topPerformanceDate, monthYearFormatter); 
+0

我不認爲設置一個月的任意一天是解決這個問題的簡單方法。 – assylias

1

我無法在文檔中找到完全定義的行爲。但我的猜測是,你需要一天才能填充臨時對象LocalDate。

試試這個:

final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("d.M.yyyy"); 
LocalDate monthYearDate = LocalDate.parse("1." + topPerformanceDate, monthYearFormatter); 
2

LocalDate表示實際人約會,所以你不能只使用了一年每月能拿到LocatDate

可以使用

YearMonth yearMonth =YearMonth.from(monthYearFormatter.parse("6.2015")); 

,你可以格式化月STR格式之前0X並使用MM.yyyy模式格式

+0

謝謝,我已糾正它。 @ Basil Basil Bourque – long