Related Question Java date time format check and reset
public static void main(String[] args) {
String inStr = "03/01/2018 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
Calendar cal = null;
try {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("M/d/[uuuu][uu][ h:m[[:ss][ ]a]][ H:m[:ss]]", Locale.US);
// parse, try to create a LocalDateTime - if it's not possible, try a LocalDate
TemporalAccessor parsed = fmt.parseBest(inStr, LocalDateTime::from, LocalDate::from);
LocalDateTime dt = null;
if (parsed instanceof LocalDateTime) {
// LocalDateTime parsed (all fields set)
dt = (LocalDateTime) parsed;
} else if (parsed instanceof LocalDate) {
// LocalDate parsed (set time fields)
dt = ((LocalDate) parsed)
// set time (00:00 AM default)
.atTime(LocalTime.of(0, 0));
}
ZonedDateTime zdt = dt.atZone(ZoneId.systemDefault());
cal = GregorianCalendar.from(zdt);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(df.format(cal.getTime()));
}
Here is my code, what i am trying is parse best using the fmt and getting the output in a format "MM/dd/yyyy hh:mm:ss a" i have unit tested with the answer provided in the related question, but today i found it is failing for the input "03/01/2018 00:00:00". i could figure out the issue, the above code is trying to parse in format "[ h:m[[:ss][ ]a]]" instead of [ H:m[:ss]], so is that the expected behavior ? Or is there any thing i have to change the format so that parseBest will work for my inStr.?