Search code examples
javadatelocaldate

Special string to LocalDate


From the following String I want to get the LocalDate or LocalDateTime.

Jan 1, 2019 12:00:00 AM

I have already tried the following code but I am getting the following error:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy hh:mm:ss a"); // also with dd
formatter = formatter.withLocale(Locale.GERMAN);
LocalDateTime localDateTime = LocalDateTime.parse(stringDate, formatter);
LocalDate localDate = LocalDate.parse(stringDate, formatter);
  • Exception in thread "main" java.time.format.DateTimeParseException: Text 'Jan 1, 2019 12:00:00 AM' could not be parsed at index 0

The way I would like to have the date, in the end, would be like

  • 01.01.2019. LocalDate
  • 01.01.2019. 12:00 LocalDateTime (24h)

Is this even possible? Would be instead the use of regular expressions an overkill?


Solution

  • There are a few problems with your code, but I will propose a working solution here:

    1. HH is the hour of the day, not the hour 0-12 (which is hh)
    2. you should use a DateTimeFormatterBuilder
    3. you should use the proper locale, probably GERMANY instead of GERMAN
    4. the name of the month is represented as L, not as M
    5. the german locale uses vorm. and nachm. instead of AM and PM -> a quick solution is to replace the terms

    Putting it all together leaves us with this:

    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.util.Locale;
    
    class Scratch {
    
        public static void main(String[] args) {
            String stringDate = "Jan 1, 2019 11:00:00 PM";
            stringDate = stringDate.replace("AM", "vorm.");
            stringDate = stringDate.replace("PM", "nachm.");
            DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .appendPattern("LLL d, yyyy hh:mm:ss a")
                    .toFormatter(Locale.GERMANY);
            LocalDateTime localDateTime = LocalDateTime.parse(stringDate, formatter);
            LocalDate localDate = LocalDate.parse(stringDate, formatter);
        }
    
    }
    

    If anybody has a different approach to handling the AM/vorm.-dilemma, I would be glad to see it!