Explain Codes LogoExplain Codes Logo

How can I parse/format dates with LocalDateTime? (Java 8)

java
date-formatting
localdatetime
datetimeformatter
Nikita BarsukovbyNikita Barsukov·Jan 14, 2025
TLDR

Ensure you are using DateTimeFormatter for parsing and formatting on LocalDateTime:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formatted = LocalDateTime.now().format(fmt); // "2023-04-01 12:00:00" or "party time?" LocalDateTime parsed = LocalDateTime.parse("2023-04-01 12:00:00", fmt);

Ensure your pattern in ofPattern matches the desired date-time format. Quite like dressing for the ocassion, match your clothes (pattern) to the event (date-time format).

Dealing with Date and Time in Java

Java's LocalDateTime and DateTimeFormatter are like a great tandem for parsing and formatting dates ensuring you can easily convert between the human-readable strings and machine's favorite date-time formats.

Parsing ISO 8601

The DateTimeFormatter is designed to work with ISO 8601 formatted date-time strings out of the box. If you have an ISO formatted string handy, you can parse it directly:

// Who needs patterns? LocalDateTime parsed = LocalDateTime.parse("2023-04-01T12:00:00");

Formatting using Predefined Formats

You can also format a LocalDateTime object using one of the predefined formats in DateTimeFormatter, see example below:

// Is it the future already? String formatted = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);

Custom Formatting

Sometimes, simplicity doesn't cut it and a more custom format is needed. Consider using DateTimeFormatter.ofPattern(). This allows you to specify your own pattern for formatting the LocalDateTime:

// Context matters DateTimeFormatter customFmt = DateTimeFormatter.ofPattern("E, MMM dd yyyy HH:mm:ss");

Don't forget, the pattern letters are symbols standing for different components of the date and time. Just as "S" for seconds, not for Superman!

Time Zones, Offsets, and Boundaries

DateTimeFormatter also copes with time zones and offsets. Always consider the impact of these on parsing and formatting:

// Don't forget, the world is round DateTimeFormatter fmtWithZone = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("UTC"));

For the Perfectionists

Resolver Policies

To handle ambiguous dates, DateTimeFormatter provides a ResolverStyle policy which controls the level of strictness it applies when parsing dates. So, if your date tends to be as uncertain as a weather forecast, make sure to define your policy.

Consider Localization

For internationalization, don't miss the handy method DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM) coupled with .withLocale(Locale.FRENCH). Remember that the default locale is not always adequate.

Accurate Parsing

Remember, for precise parsing adapt your DateTimeFormatter to ResolverStyle.STRICT. Otherwise, there's the forgiving ResolverStyle.SMART.