Explain Codes LogoExplain Codes Logo

How to format LocalDate to string?

java
datetimeformatter
localdate
date-formatting
Nikita BarsukovbyNikita Barsukov·Nov 9, 2024
TLDR

Here is a quick recipe for converting LocalDate to String using DateTimeFormatter:

LocalDate date = LocalDate.now(); // Prints today's date in "dd/MM/yyyy" format. Pretty standard, huh? String formattedDate = date.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

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:

Locale locale = Locale.FRENCH; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy", locale); // Surprise, we're in Paris now! Enjoy the French dates. String formattedDate = date.format(formatter);

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:

String formattedDate = date.format(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:

ZonedDateTime zonedDate = date.atStartOfDay(ZoneId.systemDefault()); String formattedZonedDate = zonedDate.format(DateTimeFormatter.ofPattern("dd MMMM yyyy z"));

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:

try { LocalDate date = LocalDate.parse("01-04-2023", formatter); } catch (DateTimeParseException e) { // Oops, we tripped over a pattern! Time to debug. e.printStackTrace(); }

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!