2

I am trying to convert a string to date format with Java8 using DateTimeFormatter in spring boot, But I receive an error [[java.time.format.DateTimeParseException: Text '10-03-2021' could not be parsed at index 0]]. I am using LocalDate because I want my output to have only date without time. What Am I doing wrong in my code.

    String date= "10-03-2021"
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy",Locale.forLanguageTag("sw-TZ"));
    LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
    System.out.println(dateTime.format(formatter)); 
Gabriel Rogath
  • 528
  • 1
  • 4
  • 16
  • 4
    Your are attempting to parse "10-03-2021" using the pattern designed for output: "EEEE, MMM d, yyyy". Your input needs its own formatter. – bliss Mar 10 '21 at 04:47

1 Answers1

5

You need to parse date in dd-MM-yyyy pattern first and then format it to the pattern of your choice.

String date= "10-03-2021";
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate =  LocalDate.parse(date, format);
        
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy",Locale.forLanguageTag("sw-TZ"));
System.out.println(localDate.format(formatter));
Nimantha
  • 5,793
  • 5
  • 23
  • 56
Daddys Code
  • 541
  • 1
  • 8