Search code examples
javaspringspring-bootjava-streamlocaldate

All date output bug between two dates


This is a method that prints out all dates between two dates. But as the year goes by, the December part is going to add another year. There's an bug.

It's a Korean date. Sorry for the translator.

String startDate = "2019-12-23";
String endDate = "2020-01-01";

LocalDate start = LocalDate.parse(startDate);
LocalDate end = LocalDate.parse(endDate).plusDays(1);
List<String> dates = Stream.iterate(start, date -> date.plusDays(1))
    .limit(ChronoUnit.DAYS.between(start, end))
    .map(date -> date.format(DateTimeFormatter.ofPattern("YYYYMMdd")))
    .collect(Collectors.toList());


System.err.println(dates);

bug: [20191223, 20191224, 20191225, 20191226, 20191227, 20191228, 20201229, 20201230, 20201231, 20200101]


Solution

  • Use BASIC_ISO_DATE and it will fix your problem

    List<String> dates = Stream.iterate(start, date -> date.plusDays(1))
                    .limit(ChronoUnit.DAYS.between(start, end))
                    .map(date -> date.format(DateTimeFormatter.BASIC_ISO_DATE))
                    .collect(Collectors.toList());
    
    
    System.err.println(dates);