How to format LocalDate to string?
Here is a quick recipe for converting LocalDate
to String
using DateTimeFormatter
:
This gives you a date such as "30/04/2023". Remember, you can pull the strings here, so tailor this pattern to your needs!
In-depth tutorial
Making the magic happen
Enough of 'Hello World', let's twirl DateTimeFormatter
's magic wand and transform LocalDate
with some patterns:
- Full Month:
"dd MMMM yyyy"
outputs "30 April 2023". - Shorty:
"dd MMM yyyy"
converts to "30 Apr 2023". - Spoilers:
"yyyy/MM/dd"
inverts to "2023/04/30".
Mastering the art of localization
Localization in a nutshell — don’t push your Locale
onto others:
This script turns you into a language chameleon, converting months to French!
No need to reinvent the wheel
Confused about the patterns? That's why Java created DateTimeFormatter.ISO_LOCAL_DATE
:
This sticks to the ISO-8601 movie 🎬, translating into "2023-04-30".
Beware of the old rabbit hole 🎩🐇
SimpleDateFormat
might remind you of your good old java.util
days, but beware, it's not meant for java.time
!
Time zones? Consider flying with ZonedDateTime
If a time zone decides to chip in, bring ZonedDateTime
into play:
Beyond the facade
A pattern is not just skin-deep. It depicts how you want the date details. For example:
- Retro mode:
"yy"
shrinks 2023 to "23". - Pride and precision:
"uuuu"
beams it full-length: "2023".
Catch 'em all!
An incorrect pattern doesn't scare us Java folks, we catch it with DateTimeParseException
:
Walking down the memory lane
ThreeTen-Backport
comes to the rescue when stuck with Java 6 or 7. It's like sending a postcard from java.time
!
Was this article helpful?