I tried to parse the date (3 December, 2020) with format d MMMM yyyy in Polish Locale but it is unable to parse. But why the same parsing is working fine in any other locale like english, etc. Below is the code sample which is not working. Can anyone please help on this ?
Locale loc = new Locale("pl", "PL");
String date = "3 December 2020";
SimpleDateFormat sdFormat =
new SimpleDateFormat("d MMMM yyyy", loc);
sdFormat.setLenient(false);
try {
Date d = sdFormat.parse(date);
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
It seems you got confused with parsing and formatting.
Since your input date string in
English
, you need to useLocale.ENGLISH
for parsing and you need another instance ofSimpleDateFormat
withLocale("pl", "PL")
to format the obtainedjava.util.Date
object withnew Locale("pl", "PL")
.Demo:
Output:
I believe you already know that a date-time object stores just the date-time information*1and no formatting information. On printing, a date-time object prints the string returned by the
toString
implementation of its class. Also, ajava.util.Date
object does not represent a true date-time class as it stores just the milliseconds (e.g.new Date()
object is instantiated with the number of milliseconds fromJanuary 1, 1970, 00:00:00 GMT
) and when you print it, it calculates the date-time in your JVM's timezone and prints the same i.e. if your execute the following two lines at a given moment in any part of the world,you will get the same number. Check this answer for a demo.
The date-time API of
java.util
and their formatting API,SimpleDateFormat
are outdated and because of so many such hacks, they are error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.Note: 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:
*1The modern date-time API store also the timezone information. Check Overview to learn more about these classes.