DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu"); System.out.println(LocalDate.parse("08/16/2011", dateFormatter));
Output:
2011-08-16
I contribute to the modern answer. The answer in Czech is correct and was a good answer when it was written 6 years ago. Now the infamous SimpleDateFormat class, SimpleDateFormat has long been deprecated, and we are much better at java.time , the modern Java date and time API. I highly recommend you use this instead of the old time classes.
What went wrong in the code?
When I parse on 08/16/2011 using your snippet, I get Sun Jan 16 00:08:00 CET 2011 . Since the lowercase mm is in a few minutes, I get 00:08:00 (8 minutes before midnight), and since the capital letter DD for the day of the year, I get January 16th.
In java.time too, the formatting pattern strings are case sensitive, and we need to use uppercase MM for the month and lowercase dd for the day of the month.
Question: Can I use java.time with my version of Java?
Yes, java.time works great on Java 6 and later and on older and newer Android devices.
- In Java 8 and later and on new Android devices (from API level 26, as I said), a modern API is built-in.
- In Java 6 and 7, get ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, see the links below).
- On (older) Android, the version of Android ThreeTen Backport is used. It is called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp with org.threeten.bp .
communication
Ole VV Apr 07 '18 at 11:14 2018-04-07 11:14
source share