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

Viewed 787

I have a date in string and values like "18,June 2017, 5:39AM" and "01,July 2017, 9:09AM". Now I want to convert these dates to "2017-06-18 18:47:17" in this format . I have use this code:

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);

But I have got an exception:

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

How can I convert "18,June 2017, 6:47PM" to "2017-06-18 18:47:17"?

2 Answers

java.time

You are using terrible date-time classes that were supplanted by the modern java.time classes defined in JSR 310.

Define a formatting pattern to match your input.

Specify a Locale to determine the human language used for translating the name of the month, and to determine the cultural norms for deciding localization issues.

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 ) ;

See this code run live at IdeOne.com.

By the way, this formatting pattern is terrible. Educate the publisher of your data about the ISO 8601 standard.

Related