Jumping Through Time
TL;DR
When talking about date time patterns, Y
, y
and u
all mean different things in Java, and if you don’t know that it’s painful when you discover it.
Admit it, if you hadn’t looked at the TL;DR
above, what do you think
LocalDate.of(2019, 12, 30).format(DateTimeFormatter.ofPattern("MMMYY"));
would evaluate to?
Dec19
, right? RIGHT?! RIGHT?!
NO! Apparently not! It evaluates to Dec20
! Everything you thought you knew was a lie!
Why does this happen?
Because Y
apparently means a “week-based” year, and the 30th December 2019 was the Monday of the first week of 2020, so Java thinks you want 2020.
I know, crazy!
What should be used instead is y
or u
. More info here:
- https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
- https://stackoverflow.com/questions/29014225/what-is-the-difference-between-year-and-year-of-era
Makes you wonder how many things you’ve programmed by coincidence, doesn’t it?
Food for thought!