Search code examples
javalocaldatedatetimeformatter

How to convert String to LocalDate


String date = "1992-07-25";

LocalDate dt = LocalDate.parse(date);

System.out.println(dt) // 1992-07-25 ( output )

DateTimeFormatter f =  DateTimeFormatter.ofPattern("d/MM/yyyy");

String s1 = f.format(dt); 

System.out.println(s1) // 25/07/1992 ( output in string format )

I want this (String) s1 to convert into LocalDate of pattern (LocalDate - dd/MM/yyy)

Output - 25/07/1992 should be LocalDate Type, not String


Solution

  • When you are printing LocalDate instance, it is actually calling toString() method of LocalDate class. And according to javadoc 11, this method

    Outputs this date as a String, such as 2007-12-03.
    The output will be in the ISO-8601 format uuuu-MM-dd.
    

    So you are seeing, it will always print in uuuu-MM-dd format.

    Think LocalDate as a DATE just, from where you can get the info of that particular date. When you are printing LocalDate itself, it has no meaning actually. If you need to show the date in any particular format, convert it into String, which you can do already.