没有前导零的月份如何解析日期

3

我希望能够解析像月(1-12)和年份组成的日期,例如:

1.2015
12.2015

转换为LocalDate

使用以下代码时,我遇到了一个异常:

final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("M.yyyy");
LocalDate monthYearDate = LocalDate.parse(topPerformanceDate, monthYearFormatter);
< p > < em > java.time.format.DateTimeParseException:无法解析文本“6.2015”:无法从TemporalAccessor获取LocalDate:{MonthOfYear = 6,Year = 2015},类型为java.time.format.Parsed < p > 对于短月份格式,文档对我不太清楚。 < p > 编辑: 我猜问题是缺少月份的天数?

2
我不是Java专家,但你期望在解析日期中得到哪一天? - nrodic
我希望月份的日期是未定义的... - kosmičák
你将来想如何使用这种没有日期的日期? - Pshemo
那么你实际上没有一个日期。 - nrodic
我在这里前后与所有相关的类打交道,唯一能找到的是,这里应该如何处理日期。因为日期只通过提供日、月和年来完成。我会尝试始终将第一个添加到您的日期字符串和格式中。 - Rene M.
@Pshelmo,我需要获取解析的月份-年份的第一天和最后一天日期,然后调用monthYearDate.with(TemporalAdjusters.firstDayOfMonth())和monthYearDate.with(TemporalAdjusters.lastDayOfMonth())。 - kosmičák
5个回答

8

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

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

在您的补充评论中提到了需要月份的第一天和最后一天:
LocalDate firstOfMonth = ym.atDay(1);
LocalDate endOfMonth = ym.atEndOfMonth();

3

看起来问题确实是缺少了月份中的某一天。我的解决方法是将其设置为:

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

我认为设定一个任意的月份日期并不是解决这个问题的优雅方式。 - assylias

2

LocalDate代表实际的日期,因此您不能仅使用年份和月份来获取LocalDate。

您可以使用

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

你可以将月份字符串格式化为0x,然后使用MM.yyyy格式来进行格式化。


1
我无法在文档中找到行为的确切定义。但我的猜测是,您需要一天来完成临时对象LocalDate。
尝试这个:
final DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("d.M.yyyy");
LocalDate monthYearDate = LocalDate.parse("1." + topPerformanceDate, monthYearFormatter);

-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);
}

都试过了,甚至是L.yyyy,结果在所有情况下都抛出了异常。 - kosmičák
@kosmičák 嗯,好的,看起来你通过添加日期修复了它...奇怪。 - nafas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接