Since nearly the beginning of Java, Java developers have worked with dates and times via the java.util.Date class (since JDK 1.0) and then the java.util.Calendar class (since JDK 1.1). During this time, hundreds of thousands (or maybe millions) of Java developers have formatted and parsed Java dates and times using java.text.DateFormat and java.text.SimpleDateFormat. Given how frequently this has been done over the years, it's no surprise that there are numerous online examples of and tutorials on parsing and formatting dates and times with these classes. The classic Java Tutorials cover these java.util and java.text classes in the Formatting lesson (Dates and Times). The new Date Time trail in the Java Tutorials covers Java 8's new classes for dates and times and their formatting and parsing. This post provides examples of these in action.
Before demonstrating Java 8 style date/time parsing/formatting with examples, it is illustrative to compare the Javadoc descriptions for DateFormat/SimpleDateFormat and DateTimeFormatter. The table that follows contains differentiating information that can be gleaned directly or indirectly from a comparison of the Javadoc for each formatting class. Perhaps the most important observations to make from this table are that the new DateTimeFormatter is threadsafe and immutable and the general overview of the APIs that DateTimeFormatter provides for parsing and formatting dates and times.
Characteristic
DateFormat/SimpleDateFormat
DateTimeFormatter
Purpose
"formats and parses dates or time in a language-independent manner"
"Formatter for printing and parsing date-time objects."
Primarily Used With
java.util.Date
java.util.Calendar
java.time.LocalDate
java.time.LocalTime
java.time.LocalDateTime
java.time.OffsetTime
java.time.OffsetDateTime
java.time.ZonedDateTime
java.time.Instant
Thread Safety
"Date formats are not synchronized."
"This class is immutable and thread-safe."
Direct Formatting
format(Date)
format(TemporalAccessor)
Direct Parsing
parse(String)
parse(CharSequence, TemporalQuery)
Indirect Formatting
None [unless you use Groovy's Date.format(String) extension)]
LocalDate.format(DateTimeFormatter)
LocalTime.format(DateTimeFormatter)
LocalDateTime.format(DateTimeFormatter)
OffsetTime.format(DateTimeFormatter)
OffsetDateTime.format(DateTimeFormatter)
ZonedDateTime.format(DateTimeFormatter)
Indirect Parsing
None [unless you use deprecated Date.parse(String) or Groovy's Date.parse(String, String) extension]
LocalDate.parse(CharSequence, DateTimeFormatter)
LocalTime.parse(CharSequence, DateTimeFormatter)
LocalDateTime.parse(CharSequence, DateTimeFormatter)
OffsetTime.parse(CharSequence, DateTimeFormatter)
OffsetDateTime.parse(CharSequence, DateTimeFormatter)
ZonedDateTime.parse(CharSequence, DateTimeFormatter)
Internationalization
java.util.Locale
java.util.Locale
Time Zone
java.util.TimeZone
java.time.ZoneId
java.time.ZoneOffset
Predefined Formatters
None, but does offer static convenience methods for common instances:
getDateInstance()
getDateInstance(int)
getDateInstance(int, Locale)
getDateTimeInstance()
getDateTimeInstance(int, int)
getDateTimeInstance(int, int, Locale)
getInstance()
getTimeInstance()
getTimeInstance(int)
getTimeInstance(int, Locale)
ISO_LOCAL_DATE
ISO_LOCAL_TIME
ISO_LOCAL_DATE_TIME
ISO_OFFSET_DATE
ISO_OFFSET_TIME
ISO_OFFSET_DATE_TIME
ISO_ZONED_DATE_TIME
BASIC_ISO_DATE
ISO_DATE
ISO_DATE_TIME
ISO_ORDINAL_DATE
ISO_INSTANTISO_WEEK_DATE
RFC_1123_DATE_TIME
The remainder of this post uses examples to demonstrate formatting and parsing dates in Java 8 with the java.time constructs. The examples will use the following string patterns and instances.
Before Java 8, the standard Java approach for dates and times was via the Date and Calendar classes and the standard approach to parsing and formatting dates was via DateFormat and SimpleDateFormat. The next code listing demonstrates these classical approaches.
Formatting and Parsing Java Dates with SimpleDateFormat
With Java 8, the preferred date/time classes are no longer in the java.util package and the preferred date/time handling classes are now in the java.time package. Similarly, the preferred date/time formatting/parsing classes are no longer in the java.text package, but instead come from the java.time.format package.
The java.time package offers numerous classes for modeling dates and/or times. These include classes that model dates only (no time information), classes that model times only (no date information), classes that model date and time information, classes that use timezone information, and classes that do not incorporate time zone information. The approach for formatting and parsing these is generally similar, though the characteristics of the class (whether it supports date or time or timezone information, for example) affects which patterns that can be applied. In this post, I use the ZonedDateTime class for my examples. The reason for this choice is that it includes date, time, and time zone information and allows me to use a matching pattern that involves all three of those characteristics like a Date or Calendar instance does. This makes it easier to compare the old and new approaches.
The DateTimeFormatter class provides ofPattern methods to provide an instance of DateTimeFormatter based on the provided date/time pattern String. One of the format methods can then be called on that instance of DateTimeFormatter to get the date and/or time information formatted as a String matching the provided pattern. The next code listing illustrates this approach to formatting a String from a ZonedDateTime based on the provided pattern.
Formatting ZonedDateTime as String
Parsing a date/time class from a String based on a pattern is easily accomplished. There are a couple ways this can be accomplished. One approach is to pass the instance of DateTimeFormatter to the static ZonedDateTime.parse(CharSequence, DateTimeFormatter) method, which returns an instance of ZonedDateTime derived from the provided character sequence and based on the provided pattern. This is illustrated in the next code listing.
Parsing ZonedDateTime from String Using Static ZonedDateTime.parse Method
A second approach to parsing ZonedDateTime from a String is via DateTimeFormatter's parse(CharSequence, TemporalQuery<T>) method. This is illustrated in the next code listing which also provides an opportunity to demonstrate use of a Java 8 method reference (see ZonedDateTime::from).
Parsing ZonedDateTime from String Using DateTimeFormatter.parse Method
Very few projects have the luxury of being a greenfield project that can start with Java 8. Therefore, it's helpful that there are classes that connect the pre-JDK 8 date/time classes with the new date/time classes introduced in JDK 8. One example of this is the ability of JDK 8's DateTimeFormatter to provide a descending instance of the pre-JDK 8 abstract Format class via the DateTimeFormatter.toFormat() method. This is demonstrated in the next code listing.
Accessing Pre-JDK 8 Format from JDK 8's DateTimeFormatter
The Instant class is especially important when working with both pre-JDK 8 Date and Calendar classes in conjunction with the new date and time classes introduced with JDK 8. The reason Instant is so important is that java.util.Date has methods from(Instant) and toInstant() for getting a Date from an Instant and getting an Instant from a Date respectively. Because Instant is so important in migrating pre-Java 8 date/time handling to Java 8 baselines, the next code listing demonstrates formatting and parsing instances of Instant.
Formatting and Parsing Instances of Instant
All of the above examples come from the sample class shown in the next code listing for completeness.
DateFormatDemo.java
The output from running the above demonstration is shown in the next screen snapshot.
Conclusion
The JDK 8 date/time classes and related formatting and parsing classes are much more straightforward to use than their pre-JDK 8 counterparts. This post has attempted to demonstrate how to apply these new classes and to take advantage of some of their benefits.
Original posting available at http://marxsoftware.blogspot.com/ (Inspired by Actual Events)