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 }
To format the localdate in any other custom pattern, we must use LocalDate. format(DateTimeFormatter) method. LocalDate today = LocalDate. now(); String formattedDate = today.
The toString() method of a LocalDate class is used to get this date as a String, such as 2019-01-01. The output will be in the ISO-8601 format uuuu-MM-dd. Parameters: This method does not accepts any parameters. Return value: This method returns String which is the representation of this date, not null.
DateTimeFormatter fmt = DateTimeFormatter. ofPattern("yyyy-MM-dd'T'HH:mm:ss"); System. out. println(ldt.
Another way to create a LocalDate is to create it from year, month and day information, like this: LocalDate localDate2 = LocalDate. of(2015, 12, 31); The LocalDate 's of() method creates a LocalDate instance representing a specific day of a specific month of a specific year, but without time zone information.
EDIT: Considering your edit, just set parsedDate equal to your formatted text string, like so:
parsedDate = text;
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
DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu"); String text = date.format(formatters);
Just format the date while printing it out:
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); System.out.println("Text format " + text); System.out.println("parsedDate: " + parsedDate.format(formatters)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With