How can I parse/format dates with LocalDateTime? (Java 8)
Ensure you are using DateTimeFormatter
for parsing and formatting on LocalDateTime
:
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:
Formatting using Predefined Formats
You can also format a LocalDateTime
object using one of the predefined formats in DateTimeFormatter
, see example below:
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
:
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:
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
.
Was this article helpful?