DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
System.out.println(LocalDate.parse("08/16/2011", dateFormatter));
Output:
2011-08-16
I am contributing the modern answer. The answer by Bohemian is correct and was a good answer when it was written 6 years ago. Now the notoriously troublesome SimpleDateFormat class is long outdated and we have so much better in java.time, the modern Java date and time API. I warmly recommend you use this instead of the old date-time classes.
What went wrong in your code?
When I parse 08/16/2011 using your snippet, I get Sun Jan 16 00:08:00 CET 2011. Since lowercase mm is for minutes, I get 00:08:00 (8 minutes past midnight), and since uppercase DD is for day of year, I get 16 January.
In java.time too format pattern strings are case sensitive, and we needed to use uppercase MM for month and lowercase dd for day of month.
Question: Can I use java.time with my Java version?
Yes, java.time works nicely on Java 6 and later and on both older and newer Android devices.
- In Java 8 and later and on new Android devices (from API level 26, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp with subpackages.
Links
java.util.Date,java.util.Calendar, andjava.text.SimpleDateFormatare now legacy, supplanted by the java.time classes built into Java 8 and later. See modern correct Answer by Ole V.V.