天天看點

java月份去0_java – 使用月份解析日期而不是前導0

我想解析包含月份(1-12)和年份的日期,例如:

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,Year = 2015},ISO類型為java.time.format.Parsed的ISO

在短月份格式中,documentation對我來說并不清楚.

編輯:我想問題是每月缺少的一天?

解決方法:

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

String input = "1.2015";

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

在評論中,您添加了需要該月的第一天和最後一天:

LocalDate firstOfMonth = ym.atDay(1);

LocalDate endOfMonth = ym.atEndOfMonth();

标簽:java,datetime,java-8

來源: https://codeday.me/bug/20190715/1466275.html