使用月份解析日期而不是前导0

时间:2015-07-01 10:16:10

标签: java datetime java-8

我想解析包含月份(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在短月份格式中对我来说并不清楚。

编辑:我猜问题是一月中缺少的一天?

5 个答案:

答案 0 :(得分:8)

由于您的输入不是日期而是月/年组合,我建议使用YearMonth类:

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

在评论中,您添加了一个月的第一天和最后一天:

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

答案 1 :(得分:3)

似乎问题实际上是一个月中缺失的一天。我的解决方法是设置它:

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

答案 2 :(得分:2)

LocalDate表示实际日期,因此您无法仅使用一年零一个月来获取LocatDate

你可以使用

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

并且可以在格式化之前将月份str格式化为0x并使用MM.yyyy模式格式化

答案 3 :(得分:1)

我无法找到文档中行为的确切定义。但我的猜测是你需要一天来填充时态对象LocalDate。

试试这个:

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

答案 4 :(得分:-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);
}
相关问题