Home > database >  Format date from String to LocalDate
Format date from String to LocalDate

Time:09-06

I have a problem parsing a String to LocalDate.
According to similar questions on Stackoverflow and documentation I am using the correct values ​​dd (day of the month), MM (month of the year) and yyyy (year).

My String

String mydate = "18.10.2022 07:50:18";

My parsing test code

System.out.println(
    LocalDate.parse(testPasswordExp)
             .format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")
    )
);

Error:

Caused by: java.lang.RuntimeException:
java.time.format.DateTimeParseException:
Text '18.10.2022 07:50:18' could not be parsed at index 0

CodePudding user response:

The main problem of your code example is that you first parse the String to a LocalDate without the use of a suitable DateTimeFormatter and then format() it with a DateTimeFormatter that tries to format hour of day, minute of hour and second of minute which just aren't there in a LocalDate.

You can parse this String to a LocalDate directly, but better parse it to a LocalDateTime because your String contains more than just information about

  • day of month
  • month of year
  • year

Your myDate (and probably the testPasswordExp, too) has a time of day. You can get a LocalDate as the final result that way, too, because a LocalDateTime can be narrowed down toLocalDate().

A possible way:

public static void main(String[] args) {
    // example datetime
    String testPasswordExp = "18.10.2022 07:50:18";
    
    System.out.println(
        LocalDateTime   // use a LocalDateTime and…
            .parse(     // … parse …
                testPasswordExp,    // … the datetime using a specific formatter,
                DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm:ss")
            ).toLocalDate() // then extract the LocalDate
    );
}

Output:

2022-10-18

CodePudding user response:

You don't use the specified format for parsing, you use it to format the parsed date.

LocalDate.parse(mydate)

uses the default ISO_LOCAL_DATE format. You are looking for this overload:

LocalDate.parse(mydate, DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"))

This method uses the specified format for parsing string to date.

Note that you are using LocalDate, meaning it will throw away the time part, keeping only the date after parsing. You probably meant to use LocalDateTime.

CodePudding user response:

You can use

    String mydate = "18.10.2022 07:50:18";


    LocalDate ld = LocalDate.parse(mydate, DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));

    System.out.println(ld.toString());
  • Related