Lenient Java 8 Date parsing

前端 未结 4 2222
無奈伤痛
無奈伤痛 2020-12-18 04:47

I\'d like to parse \'2015-10-01\' with LocalDateTime. What I have to do is

LocalDate localDate = LocalDate.parse(\'2015-10-01\');
LocalDateTime          


        
4条回答
  •  半阙折子戏
    2020-12-18 05:14

    A simple solution for your particular use case is to define your own format. In this example even though I have specified a single M for the month in my pattern, and a single d for the day, it still parses both examples the same.

    @Test
    public void parsing_singleDigitDates_andDoubleDigitDates_areEqual()
    {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-M-d");
    
        LocalDate dt1 = LocalDate.parse("2015-09-05", fmt);
        LocalDate dt2 = LocalDate.parse("2015-9-5", fmt);
    
        Assert.assertEquals(dt1, dt2);
    }
    

    I decided to write this answer after seeing the code soup that DateTimeFormatterBuilder requires you to write in order to solve the same problem.

提交回复
热议问题