'Java LocalDate invalid date formatting
I have a script to get previous month for current date (script executed on 1st date monthly) the script return valid result for all other month except on January
I tried to reproduce the case with these script
import java.time.*;
class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.of(2022, 1, 1);
LocalDate prevMonth = today.minusDays(1);
System.out.println("Date object " + prevMonth);
System.out.println("Date formatted " + prevMonth.format(DateTimeFormatter.ofPattern("YYYY-MM-dd")));
}
}
Output:
Date object 2021-12-31
Date formatted 2022-12-31
Environment
openjdk 11.0.11 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.18.04)
OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.18.04, mixed mode, sharing)
Where is the bug come from, or you have better idea ?
PS: I preferred LocalDate over calendar
Solution 1:[1]
You really need to carefully read the docs.
Do not use Y
.
Y means 'weekyear'. You really, really, really do not want this. It'll turn 2022 somewhere around jan 1st, but not on jan 1st (well, one it about 7 years or so, it manages to line up perfectly). There will be days in year X that have a weekyear of year (X+1), and there will be days in year Z that will have a weekyear of year (Z-1): After all, a week starts on monday, so 'weekyear' can't change except on mondays. Turns out Jan 1st? Not always a Monday.
You want u
. y
is always great, but y does silly things for years before the year 0. Aside from that, u
and y
are identical. In other words, u
is just better, it's the one you should use.
You also do not want D
.
D means day-of-year. You wanted day-of-month. That's the symbol d
(lowercase).
Try "uuuu-MM-dd"
.
Solution 2:[2]
Uppercase 'D' is Day of year, not day of month.
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
You are likely looking for 'd' - Day of Month.
DateTimeFormatter.ofPattern("YYYY-MM-dd")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rzwitserloot |
Solution 2 | Brian |