I am new to using DateTimeFormatter package, and same thing we are able to get using SimpleDateFormat.
Date date = new SimpleDateFormat("MMMM").parse(month);//"DECEMBER"
Date date = new SimpleDateFormat("yyyy").parse(year);//"2020"
How to achive this using DateTimeFormatter?
The date-time API of
java.util
and their formatting API,SimpleDateFormat
are outdated and error-prone. Let's see them in action:Output:
I do not need to explain what defaults they are taking. Instead of taking such unexpected defaults, they should have raised an alarm (throw some exception) which would have become helpful to a programmer to react to.
Because of such surprises, it is recommended to stop using them completely and switch to the modern date-time API.
Note: For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
Output:
So, now you (the programmer) get to know that you have to do something (e.g. use your own defaults) to parse the strings.
Demo:
Output:
If you do not want to create a date or date-time object, rather, if all you want to do is to parse your string into
Month
andYear
, you can do it simply the following way:Output:
Learn more about the modern date-time API at Trail: Date Time.