我在尝试以下代码时遇到解析异常:
String date="Sat Jun 01 12:53:10 IST 2013";
SimpleDateFormat sdf=new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
Date currentdate;
currentdate=sdf.parse(date);
System.out.println(currentdate);
异常(exception):
Exception in thread "main" java.text.ParseException: Unparseable date: "Sat Jun 01 12:53:10 IST 2013" at com.ibm.icu.text.DateFormat.parse(DateFormat.java:510)
输入:Sat Jun 01 12:53:10 IST 2013
预期输出:Jun 01,2013 12:53:10
如何解决?
最佳答案
您的模式根本与输入字符串不对应...它不起作用也就不足为奇了。这可能会更好:
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
然后,要使用您需要的格式打印,您需要第二个 SimpleDateFormat:
Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));
注意事项:
- 您应该包含区域设置,就好像您的区域设置不是英语一样,可能无法识别日期名称
- IST is ambiguous and can lead to problems因此,如果可能,您应该在输入中使用正确的时区名称。
关于java.text.ParseException : Unparseable date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16871367/