我有以下方法:
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;
}
传入的字符串格式为:
"08-11-19 07:00 AM"
明显没有引号。现在,上述方法在我的 Mac 上运行得很好,但是当我的一些用户使用该程序(在 Windows 上)时,他们会遇到异常:
java.text.ParseException: Unparseable date: "08-11-19 07:00 AM"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
操作系统在这里有什么不同吗?或者还有其他的事情在起作用吗?据我所知 SimpleDateFormat 与输入字符串完全匹配?
最佳答案
当我切换到不同的区域设置时,我可以重现该问题。
这是我的演示程序:
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);
}
}
}
当我在美国英语语言环境下运行它时,它有效:
robert@saaz:~$ LC_ALL="en_US.UTF-8" java YourCode "08-11-19 07:00 AM"
Sun Aug 11 07:00:00 CDT 2019
当我切换到德国语言环境时,我会看到您看到的异常,该语言环境使用 24 小时时间,而不是 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)
要解决此问题,请在创建 SimpleDateFormat
时指定区域设置。改变
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy hh:mm a");
至
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy hh:mm a", Locale.US);
关于Java SimpleDateFormat 抛出 ParseException : Unparseable date on Windows but not on Mac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615971/