Search code examples
javadatetimejava-timezoneddatetimedatetimeformatter

Problem with convert String to LocalDateTime


When I run this I get exception: Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-12-15 13:48:52' could not be parsed: Invalid value for ClockHourOfAmPm (valid values

I write to console: 2020-12-15 13:48:52

public class Main {
    public static void main(String[] args) {


        Scanner scanner = new Scanner(System.in);
        System.out.println("Podaj datę:");
        String input = scanner.nextLine();


        if (input.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
            DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(input, dateTimeFormatter1);
            printDateTime(localDateTime);
        } else if (input.matches("\\d{2}.\\d{2}.\\d{4} \\d{2}:\\d{2}:\\d{2}")) {
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("dd.MM.yyyy hh:mm:ss");
            LocalDateTime localDateTime2 = LocalDateTime.parse(input, dateTimeFormatter2);
            printDateTime(localDateTime2);
        } else if (input.matches("\\d{4}-\\d{2}-\\d{2}")) {
            DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime localDateTime3 = LocalDateTime.parse(input, dateTimeFormatter3);
            printDateTime(localDateTime3);
        } else {
            System.out.println("Zły format");
        }
    }

    private static void printDateTime(LocalDateTime localDateTime) {
        System.out.println("Czas lokalny: " + ZonedDateTime.now());
        System.out.println("UTC: " + ZonedDateTime.of(localDateTime, ZoneId.of("UTC")));
        System.out.println("Londyn: " + ZonedDateTime.of(localDateTime, ZoneId.of("London")));
        System.out.println("Los Angeles: " + ZonedDateTime.of(localDateTime, ZoneId.of("Los Angeles")));
        System.out.println("Sydney: " + ZonedDateTime.of(localDateTime, ZoneId.of("Sydney")));
    }
}

Solution

  • Your DateTime pattern in your DateTimeFormatter causes the problem you see here. You need to use HH instead of hh

    • hh: This is an hour-of-day pattern that uses a 12 hour clock, with AM/PM indications.
    • HH: This is an hour-of-day pattern that uses a 24 hour clock. Takes input between 0-23

    Sidenote, the zones you use seem to be invalid. The corresponding zones would be

    Europe/London
    America/Los_Angeles
    Australia/Sydney