0

Running into ZonedDateTime formatting issue. It formats end of December, 2020 dates as 2021 dates. Java snippet

ZonedDateTime z1 = ZonedDateTime.of(LocalDateTime.of(2020, 12, 31, 0, 0), ZoneId.of("America/New_York"));
z1.format(DateTimeFormatter.ofPattern("YYYY-MM-dd"))
// yields "2021-12-31"

Same goes for December 28th, 29th, 30th. Same result for different time-zones. Repeats for December 30 2019 (formats as 2020-12-30).

Original Clojure snippet

(let [zdt (ZonedDateTime/of (LocalDateTime/of 2020 12 31 0 0) (ZoneId/of "America/New_York"))
      f (DateTimeFormatter/ofPattern "YYYY-MM-dd")]
  (.format zdt f))
; => "2021-12-31"

I am able to reproduce on:

  • MacOS HotSpot Java 10 (java version "10.0.2" 2018-07-17)
  • OpenJDK version "11.0.9.1" 2020-11-04

If you're OK with Lisps – you can see it for yourself in a cloud REPL here

Abra
  • 19,142
  • 7
  • 29
  • 41
Light-wharf
  • 147
  • 1
  • 7

2 Answers2

5

Change the pattern string to yyyy-MM-dd. Refer to the javadoc for class DateTimeFormatter to understand the difference between YYYY and yyyy.

ZonedDateTime z1 = ZonedDateTime.of(LocalDateTime.of(2020, 12, 31, 0, 0), ZoneId.of("America/New_York"));
System.out.println(z1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

Result:

2020-12-31
Abra
  • 19,142
  • 7
  • 29
  • 41
2

Ok, found it. It’s just my formatting mistake.

  • Y is for week-based-year
  • y is for era year
  • u is for just year

So use "uuuu-MM-dd" and it all works

Light-wharf
  • 147
  • 1
  • 7