0

In a need to convert Java LocalDate of the format of dd-MM-yyyy into a LocalDate of dd/MM/yyyy.

Trying with :

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = // LocalDate value in dd-MM-yyyy format
String stringDate = dateFormat.format(date);
LocalDate convertedDate = LocalDate.parse(stringDate, dateFormat);

But still it resulting into return a date in dd-MM-yyyy format. Any efficient way to do this?

dinesh alwis
  • 257
  • 1
  • 3
  • 12
  • 3
    You got something fundamental wrong. `LocalDate` doesn't have a format. It's just a date object. When you print a `LocalDate` object, its `toString()` method is called, and it uses `yyyy-MM-dd` format by default (maybe that varies with locales). – ernest_k Apr 21 '20 at 09:14
  • i see. yeah that makes sense. so is there any way to achieve this? – dinesh alwis Apr 21 '20 at 09:21
  • No, @dineshalwis, there isn’t. It’s also better to keep the date in a `LocalDate` and your desired format in a `String`. – Ole V.V. Apr 21 '20 at 17:11

1 Answers1

0

The default toString implementation in LocalDate.java seems to be hardwired with '-' as a separator. So all default print statements will result into same format. Seems only way out would be to use a formatter and get a string output.

return buf.append(monthValue < 10 ? "-0" : "-")
            .append(monthValue)
            .append(dayValue < 10 ? "-0" : "-")
            .append(dayValue)
            .toString();

Also, purpose of LocalDate.parse(..) is not to convert the date format. It's actually meant to just get a date value in String and give a resulting LocalDate instance.

Hope this helps.

Abhi
  • 1
  • 2