Java 8 examples to format LocalDate to String in default patterns as well as custom date patterns.
1. Default pattern [yyyy-MM-dd]
If we use the LocalDate.toString()
method then it format the date in default format which is yyyy-MM-dd
.
- The default pattern referenced in DateTimeFormatter.ISO_LOCAL_DATE.
- DateTimeFormatter.ISO_DATE also produces the same result.
LocalDate today = LocalDate.now(); System.out.println(today.toString());
Program output.
2019-04-03
2. Custom patterns
To format the local date in any other pattern, we must use LocalDate.format(DateTimeFormatter) method.
2.1. Long, medium, short and full patterns
The DateTimeFormatter.ofLocalizedDate(FormatStyle)
supports some most used date patterns which we can directly.
LocalDate today = LocalDate.now(); String formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)); System.out.println("LONG format: " + formattedDate); formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)); System.out.println("MEDIUM format: " + formattedDate); formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)); System.out.println("SHORT format: " + formattedDate); formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)); System.out.println("FULL format: " + formattedDate);
Program output.
LONG format: April 3, 2019 MEDIUM format: Apr 3, 2019 SHORT format: 4/3/19 FULL format: Wednesday, April 3, 2019
2.2. User defined pattern
If we have a date pattern which is not available inbuilt, we can define our own pattern and use it.
LocalDate today = LocalDate.now(); String formattedDate = today.format(DateTimeFormatter.ofPattern("dd-MMM-yy")); System.out.println(formattedDate);
Program output.
03-Apr-19
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
X M
2.2 doesn’t work : java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: MinuteOfHour
hthhth
Use MM, MMM for month, mm is for minute : )