3

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
  • 167
  • 2
  • 10

3 Answers3

5

You want lowercase y -

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

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
  • 20,870
  • 14
  • 76
  • 119
3

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,368
  • 13
  • 20