3
votes

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
From your example it looks like the PM/AM-part of the input date is directly adjacent to the minute part. But in your format you got a space between minute and the am/pm-markerdpr
There is space between yyyy and ,, after removing space and code change suggested by dpr it doesn't give parse exception.deepakl

2 Answers

3
votes

you must add single quotes arround the comma and remove the blank between mm and a

 SimpleDateFormat formatter = new SimpleDateFormat("dd','MMMM yyyy',' HH:mma", Locale.ENGLISH);
1
votes

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.