0
import java.util.*; 
import java.lang.*;
import java.io.*;
import java.time.*;
import java.time.format.*;
import java.text.*;

public class ConvertStringToDate {  
    public static void main(String[] args)throws Exception { 

        String date = "2020-06-14";
        DateTimeFormatter Stringformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // convert String to LocalDate
        LocalDate localDate = LocalDate.parse(date, Stringformatter); 

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); 
        String formattedDate = localDate.format(formatter); // output here is as expected 14.06.2020
        // facing issues when converting back to localDate with defined pattern,
        LocalDate parsedDate = LocalDate.parse(formattedDate, formatter); // expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14 

        // System.out.println(parsedDate);
        // System.out.println(parsedDate.getClass().getName());

    }  
 }  

Apologizes for my explanation early days with java. Basically i am trying to convert input string "2020-06-14" into a localDate with a custom pattern "dd.MM.yyyy" in the end trying to have a date object not a String. Is there an other way to achieve it.

luk2302
  • 55,258
  • 23
  • 97
  • 137
sravan
  • 35
  • 9
  • You don’t want that, or at least, should not want that. A `LocalDate` belongs in your domain model, and there format doesn’t matter. A specific format belongs in your interface — and in a string. – Ole V.V. Jun 14 '20 at 14:52

1 Answers1

4

A date has no format. Therefore when you write

//expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14

your expectation is simply wrong. The date is parsed according to the formatter but how the date represents the parsed values and how it chooses to display them afterwards no longer has any connection to the formatter.

The only way to get your format back is to write parsedDate.format(formatter) once again and you are back where you started, which is what formattedDate was already.

luk2302
  • 55,258
  • 23
  • 97
  • 137