4

It's been a long day and my brain is tired so maybe I'm completely missing something, but how come when I run this line,

System.out.println(
  DateTimeFormatter.ofPattern("YYYYMMdd")
    .withZone(ZoneId.of("UTC"))
    .format(Instant.parse("2020-12-31T08:00:00Z"))
  )
)

I get 20211231 instead of 20201231? Where does the extra year come from?

gurdingering
  • 207
  • 5
  • 12

3 Answers3

7

You want lowercase y -

        System.out.println(
            DateTimeFormatter.ofPattern("yyyyMMdd")
                    .withZone(ZoneId.of("UTC"))
                    .format(Instant.parse("2020-12-31T08:00:00Z"))
    );
Kim
  • 150
  • 7
5

According to the docs of DateTimeFormatter, Y is the week-based year. That means that the year number of the week in which the date falls, is returned.

The fact is that 31st of December, 2020, is actually week 1 of 2021, hence 2021 is returned instead of 2020.

You probably want to use yyyy instead.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
4

The capital Y represents Week based year as per official documentation of DateTimeFormatter. More about how it calculates over here.

This works fine if you use date formatter with smallcase y as yyyyMMdd.

System.out.println(DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneId.of("UTC"))
            .format(Instant.parse("2020-12-31T08:00:00Z")));

Output:

20201231
stackFan
  • 1,528
  • 15
  • 22