3
LocalDate date = LocalDate.now();
System.out.println("date :" + date );//default format is yyyy-MM-dd
System.out.println(date.getClass().getName());//java.time.LocalDate

How to format the above date in LocalDate type with the format dd-MM-yyyy. But you can use String date pattern i.e dd-MM-yyyy. The output should be of LocalDate type only.

Freak
  • 6,786
  • 5
  • 36
  • 54
Suresh Kumar
  • 33
  • 1
  • 1
  • 5

1 Answers1

5

This feature is not a responsibility of LocalDate class which is an immutable date-time object that represents a date. Its duty is not to care about the String format representation.

To generate or parse strings, use the DateTimeFormatter class.

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String string = date.format(pattern);

Back to LocalDate, use the same pattern:

LocalDate dateParsed = LocalDate.parse(string, pattern);

But the new dateParsed will again be converted to its default String representation since LocalDate overrides toString() method. Here is what the documentation says:

The output will be in the ISO-8601 format uuuu-MM-dd.

You might want to implement your own decorator of this class which handles the formatting.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • So to format from one to another format in LocalDate itself not possible ? – Suresh Kumar Jun 21 '18 at 13:42
  • Do we need LocalDate -> String (for formatting) -> LocalDate ? – Suresh Kumar Jun 21 '18 at 13:43
  • 2
    Right, it's not possible. `LocalDate` represents the date itself, not it's format. To display the date in a different format (ex. `"dd-MM-yyyy"`), you have to format it using `DateTimeFormatter` and the produced result will be `String`. When you parse the very same `String` using the same pattern, you'll get `LocalDate` again - but `System.out.println("date :" + date );` will print exactly the same - its default representation. – Nikolas Charalambidis Jun 21 '18 at 13:46
  • 2
    Tip: Rather than hard-code a formatting pattern, you have *java.time* automatically localize by calling `DateTimeFormatter.ofLocalized…` methods. – Basil Bourque Jun 21 '18 at 16:52