-1

So, I have a class "Person" that contains a constructor with 4 parameters - 3 Strings and 1 Local Date and an overridden toString method that writes the output onto the console (it also converts the LocalDate variable to a String). Here is the code for that:

    public class Person {
    
    String name;
    String surname;
    LocalDate date;
    String placeOfBirth;
    
    Person (String name, String surname, LocalDate date, String placeOfBirth) {
        this.name = name;
        this.surname = surname;
        this.date = date;
        this.placeOfBirth = placeOfBirth;
    }
    
    public String toString () {
     
     return  name + " " + surname + " " + date.toString() + " " + placeOfBirth;

    }
}

Now, in the main method, I've created 3 different objects with different parameters and I've added all of them into an ArrayList as follows:

ArrayList lista = new ArrayList();
       
       
       lista.add(person1.toString());
       lista.add(person2.toString());
       lista.add(person3.toString());

     for (Object data: lista) {
            System.out.println(data);
        }

The program works fine, and I am getting the output in the following format:

Michael Barton 1968-01-01 Krakov

Now, I would like this date to be displayed as "01. January 1968" instead of "1968-01-01". Is there a way to format that somehow within this code?

Thanks in advance.

cuphead
  • 7
  • 3
  • 2
    A `LocalDate` has a method `format()` that takes a `DateTimeFormatter` as argument. Have a look at that. – deHaar Nov 09 '20 at 15:58

1 Answers1

-1

You can replace your toString method, with the following example:

public String toString () {
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd. MMMM yyyy");
    return  name + " " + surname + " " + date.format(dateFormatter) + " " + placeOfBirth;
  }
Andrian Soluk
  • 474
  • 6
  • 12