“ java.text.ParseException:无法解析的日期:“2017 年 6 月 18 日,5:39AM”

" java.text.ParseException: Unparseable date: "18,June 2017, 5:39AM"

我有一个字符串日期和 "18,June 2017, 5:39AM" 之类的值 "01,July 2017, 9:09AM"。现在我想将这些日期转换为这种格式的 "2017-06-18 18:47:17"。我已经使用了这个代码:

String testDate = "18,June 2017, 5:39AM";
SimpleDateFormat formatter = new SimpleDateFormat("dd,MMMM yyyy , HH:mm a", Locale.ENGLISH);
Date date = formatter.parse(testDate);
System.out.println(date);

但是我有一个例外:

Exception in thread "main" java.text.ParseException: Unparseable date: "18,June 2017, 5:39AM"
at java.text.DateFormat.parse(DateFormat.java:366)

如何将 "18,June 2017, 6:47PM" 转换为 "2017-06-18 18:47:17"

您必须在逗号周围添加单引号并删除 mma

之间的空格
 SimpleDateFormat formatter = new SimpleDateFormat("dd','MMMM yyyy',' HH:mma", Locale.ENGLISH);

java.time

您使用的日期时间 类 被 JSR 310 中定义的现代 java.time 类 所取代。

定义格式模式以匹配您的输入。

指定 Locale 以确定用于翻译月份名称的人类语言,并确定决定本地化问题的文化规范。

String input = "18,June 2017, 5:39AM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d,MMMM uuuu, h:mma").withLocale( Locale.US ) ;   
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

看到这个code run live at IdeOne.com

顺便说一句,这种格式化模式很糟糕。就 ISO 8601 标准对您的数据发布者进行培训。