You could use the Java 8 time
package:
String input = "11/23/2017 09:44am";
String format = "MM/dd/yyyy hh:mma";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDateTime date = LocalDateTime.parse(input, formatter);
System.out.printf("%s%n", date);
But the problem is: this throws a DateTimeParseException
, because of the lowercase 'am'.
I looked up in the docs, but I couldn't see a standard way to parse lowercase 'am' or 'pm' as as meridiem designator1. You'll end up manually replacing them:
input = input.replace("AM", "am").replace("PM","pm");
As mentioned by @OleVV in the comments, you can use a DateTimeFormatterBuilder
and specify that the parsing should be case-insensitive:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(format)
.toFormatter();
Then you can use this formatter as argument to the LocalDateTime.parse
method.
Another answer of the aforementioned post provides a solution where you can override the AM/PM symbols with the lowercase variants.
1 Interestingly, the SimpleDateFormat
does support the parsing of lowercase am/pm.