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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
stan92
  • 9
  • 1
  • 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) – Christoph Dahlen Nov 17 '22 at 20:28
  • 1
    Have a look at the [JavaDocs](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/time/LocalDate.html#parse(java.lang.CharSequence)) 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 – MadProgrammer Nov 17 '22 at 20:29
  • 1
    Also, you could make the DateTimeFormatter a static class member. – Christoph Dahlen Nov 17 '22 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 `return`statement too. – Ole V.V. Nov 20 '22 at 12:49
  • For your case I think that you just want `date = LocalDate.of(2022, Month.NOVEMBER, 12);`. – Ole V.V. Nov 20 '22 at 12:52
  • *I get issue that is impossible this parse*. I cannot reproduce this problem either since `default` is a keyword in java, so your code does not compile. Please instead post code that actually produces the problem that you are asking about. See [mre]. – Ole V.V. Nov 20 '22 at 13:02
  • And indeed, once you get your formatter correct, you can use it twice if you want (and also make it static as @ChristophDahlen suggests). – Ole V.V. Nov 20 '22 at 13:05

0 Answers0