erik p :
I have the following method:
public static Date convertFromWowInterface(String wowinterfaceFormat){
Date date = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy hh:mm a");
date = dateFormat.parse(wowinterfaceFormat);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
The string being passed in is of the format:
"08-11-19 07:00 AM"
without the quotes obviously. Now the above method works just fine on my mac, however when some of my users use the program (on Windows) they get the exception:
java.text.ParseException: Unparseable date: "08-11-19 07:00 AM"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
Does the OS make a difference here? Or is there something else at play? As far as I can tell the SimpleDateFormat match the input string exactly?
Robert :
I can reproduce the problem when I switch to a different locale.
Here's my demo program:
import java.util.*;
import java.text.*;
public class YourCode {
public static void main(String[] args) throws Exception {
for (String a : args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy hh:mm a");
Date d = dateFormat.parse(a);
System.out.println(d);
}
}
}
It works, when I run it under US English locale:
robert@saaz:~$ LC_ALL="en_US.UTF-8" java YourCode "08-11-19 07:00 AM"
Sun Aug 11 07:00:00 CDT 2019
I get the exception you see when I switch to e.g., German locale, which uses 24h time, not AM/PM.
robert@saaz:~$ LC_ALL="de_DE.UTF-8" java YourCode "08-11-19 07:00 AM"
Exception in thread "main" java.text.ParseException: Unparseable date: "08-11-19 07:00 AM"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
at YourCode.main(YourCode.java:8)
To get around this, specify the locale when you create the SimpleDateFormat
. Change
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy hh:mm a");
to
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy hh:mm a", Locale.US);