Java SimpleDateFormat引发ParseException:Windows上无法解析的日期,但Mac上没有 [英] Java SimpleDateFormat throwing ParseException: Unparseable date on Windows but not on Mac
问题描述
我有以下方法:
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"
显然没有引号.现在上面的方法在我的Mac上可以正常工作,但是当我的某些用户在Windows上使用该程序时,他们会收到异常:
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)
操作系统在这里是否有所作为?还是还有其他东西在玩?据我所知,SimpleDateFormat与输入字符串完全匹配吗?
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?
推荐答案
当我切换到其他语言环境时,我可以重现该问题.
I can reproduce the problem when I switch to a different locale.
这是我的演示程序:
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
当我切换到例如德国语言环境时,会看到一个例外,该语言使用24小时制,而不是AM/PM.
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)
要解决此问题,请在创建 SimpleDateFormat
时指定语言环境.更改
To get around this, specify the locale when you create the SimpleDateFormat
. Change
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:Windows上无法解析的日期,但Mac上没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!