0

I want to convert date from String to LocalDate object: Starting date as String: "12/11/2022" I want to convert this String to LocalDate. I want to get LocalDate object and next use this LocalData inside if-else conditions to convert this object to String and return String. All conditions return first LocalData and next String as result: if I use this code with: date = LocalDate.parse(default)};

public String getStringDate(String timeProjection){ 
   if (timeProjection.equals("1") { 
      date = LocalDate.now();
   }
   .... 
    else {
       String default = "12/11/2022"; 
       date = LocalDate.parse(default);
    }

 command

   return date.format(DataTimeFormatter.ofPattern("dd/MM/YYYY"));

I get issue that is impossible this parse, but when I use:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY"); 
String date = "16/08/2016"; 
LocalDate localDate = LocalDate.parse(date, formatter); 

This convertion works good. What do you think is possible create solution when I can't use twice this formatter: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY") - first in else body, second in result command? Thanks for your help.

7
  • 1
    JavaDocs for LocaDate.parse(String) say: "Obtains an instance of LocalDate from a text string such as 2007-12-03.". So, yes - you need to supply a formatter. Or - for fixed dates, use LocalDate.of(int,int.int) Commented Nov 17, 2022 at 20:28
  • 1
    Have a look at the JavaDocs for LocalDate.parse - it expects a string in the format of “yyyy-MM-dd” - you need to use a DateTimeFormatter which better matches your input Commented Nov 17, 2022 at 20:29
  • 1
    Also, you could make the DateTimeFormatter a static class member. Commented Nov 17, 2022 at 20:30
  • I cannot get your last snippet to work either. I get DateTimeParseException: Text '16/08/2016' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=16, WeekBasedYear[WeekFields[SUNDAY,1]]=2016, MonthOfYear=8},ISO of type java.time.format.Parsed. This is because upper case YYYY is wrong. Use either lower case uuuu or lower case yyyy. In your returnstatement too. Commented Nov 20, 2022 at 12:49
  • For your case I think that you just want date = LocalDate.of(2022, Month.NOVEMBER, 12);. Commented Nov 20, 2022 at 12:52

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.