Java 8 Time API: how to parse string of format “MM.yyyy” to LocalDate

后端 未结 2 1192
面向向阳花
面向向阳花 2020-12-14 13:53

I\'m a bit discouraged with parsing dates in Java 8 Time API.

Previously I could easily write:

String date = \"04.2013\";
DateFormat df = ne         


        
2条回答
  •  温柔的废话
    2020-12-14 14:32

    Following alternative is probably not so nice but at least a successfully tested solution, too, so I mention it here for completeness and as supplement to the right answer of @assylias:

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    builder.parseDefaulting(ChronoField.DAY_OF_MONTH, 1);
    builder.append(DateTimeFormatter.ofPattern("MM.yyyy"));
    DateTimeFormatter dtf = builder.toFormatter();
    
    String ym = "04.2013";
    LocalDate date = LocalDate.parse(ym, dtf);
    System.out.println(date); // output: 2013-04-01
    

提交回复
热议问题