I am reading text and storing the dates as LocalDate variables.
Is there any way for me to preserve the formatting from DateTimeFormatter so that when I call the LocalDate variable it will still be in this format.
EDIT:I want the parsedDate to be stored in the correct format of 25/09/2016 rather than printing as a string
My code:
public static void main(String[] args)
{
LocalDate date = LocalDate.now();
DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu");
String text = date.format(formatters);
LocalDate parsedDate = LocalDate.parse(text, formatters);
System.out.println("date: " + date); // date: 2016-09-25
System.out.println("Text format " + text); // Text format 25/09/2016
System.out.println("parsedDate: " + parsedDate); // parsedDate: 2016-09-25
// I want the LocalDate parsedDate to be stored as 25/09/2016
}
This could be possible if you could extend LocalDate and override the
toString()
method but the LocalDate class is immutable and therefore (secure oop) final. This means that if you wish to use this class the onlytoString()
method you will be able to use is the above (copied from LocalDate sources):If you must override this behavior, you could box LocalDate and use your custom
toString
method but this could cause more problems than it solves!Short answer: no.
Long answer: A
LocalDate
is an object representing a year, month and day, and those are the three fields it will contain. It does not have a format, because different locales will have different formats, and it will make it more difficult to perform the operations that one would want to perform on aLocalDate
(such as adding or subtracting days or adding times).The String representation (produced by
toString()
) is the international standard on how to print dates. If you want a different format, you should use aDateTimeFormatter
of your choosing.Just format the date while printing it out:
EDIT: Considering your edit, just set parsedDate equal to your formatted text string, like so:
A LocalDate object can only ever be printed in ISO8601 format (yyyy-MM-dd). In order to print the object in some other format, you need to format it and save the LocalDate as a string like you've demonstrated in your own example