1

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.?

Pat
  • 535
  • 1
  • 16
  • 41
  • 1
    By the way… why are you mixing the troublesome legacy classes (`SimpleDateFormat`, `Calendar`, `GregorianCalendar`) with the modern *java.time* classes (`LocalDateTime`, `DateTimeFormatter`)? Do you understand that the *java.time* classes completely supplanted the legacy date-time classes? – Basil Bourque Apr 10 '18 at 20:32

1 Answers1

3

Because you have [[:ss][ ]a] as optional, [ h:m[[:ss][ ]a]] is matching as [ h:m]. You should require the a there and let [ H:m[:ss]] handle the h:m case.

"M/d/[uuuu][uu][ h:m[:ss][ ]a][ H:m[:ss]]"
Sean Van Gorder
  • 3,393
  • 26
  • 26