1

I was running some code and was getting a strange error I could not understand. So i tried to debug it and ran multiple test and found this this is the code I am running

@Test
public void test(){

    LocalDate firstDay = LocalDate.parse("2020-12-01");
    LocalDate lastDay = LocalDate.parse("2020-12-31");

    String firstDayString = firstDay.format(DateTimeFormatter.ofPattern("YYYYMMdd"));
    String lastDayString = lastDay.format(DateTimeFormatter.ofPattern("YYYYMMdd"));

    System.out.println(firstDayString);
    System.out.println(lastDayString);

}

And this is the output

20201201
20211231

please note the year for the last date changed to 2021 when i tried to do the format. Any one else has notice this?

rread
  • 143
  • 1
  • 13
  • 1
    You should use `yyyy` not `YYYY` - Possible duplicate of: https://stackoverflow.com/q/26431882/150978 – Robert Jun 24 '21 at 15:40

1 Answers1

5

Your format is incorect if you are expecting 2020 for both dates. Change it to yyyyMMdd

  • y (lowercase) is year
  • Y (uppercase) is 'week-based-year'

Worth a read: yyyy-vs-yyyy-the-day-the-java-date-formatter-hurt-my-brain

Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • 1
    20 years developing in java and first time i notice this – rread Jun 24 '21 at 15:46
  • @rread A) one never stops learning and b) working with date and time always brings new surprises. I was working with the ethiopian calendar last week, which has 13 months per year, to implement an adapter in java, – Eritrean Jun 24 '21 at 15:57