Search code examples
javadatetime-formatlocaldatetimedatetimeformatter

How do I parse "Nov 20, 2016 12:00:00 AM" to LocalDateTime?


I found very interesting bug or something like that.

I use this date format MMM d, yyyy hh:mm:ss a and it will prints date like this

Aug 13, 2020 01:19:50 pm

But, when I parse Nov 20, 2016 12:00:00 AM to LocalDateTime, it throws the exception

java.time.format.DateTimeParseException: Text 'Nov 20, 2016 12:00:00 AM' could not be parsed at index 22.

After I change 'AM' to 'am' it works perfectly! so LocalDateTime literally cannot parse date because of uppercase a̶p̶e̶s̶ letters? And how can I solve this problem, without replacing 'AM' to 'am' and 'PM' to 'pm'

EDIT

SimpleDateTime format doesn't have this problem, he ignores the a̶p̶e̶s̶ letters register (i mean uppercase or lowercase) And I would not like to convert Date to LocalDateTime

EDIT 2

MMM d, yyyy hh:mm:ss A replace 'a' to 'A' also didn't work


Solution

  • You need to parse it in a case-insensitive way. Also, make sure to use an English locale (e.g. Locale.ENGLISH, Locale.US etc.) because the names of elements are represented with localized strings in the corresponding locales.

    Demo:

    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            // Given date-time string
            String strDateTime = "Nov 20, 2016 12:00:00 AM";
    
            // Define the formatter
            DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                            .parseCaseInsensitive()
                                            .appendPattern("MMM d, u h:m:s a")                                       
                                            .toFormatter(Locale.ENGLISH);                                     
    
            // Parse the given date-time into LocalDateTime using formatter
            LocalDateTime ldt = LocalDateTime.parse(strDateTime, formatter);
    
            System.out.println(ldt);
        }
    }
    

    Output:

    2016-11-20T00:00