Formatting and Parsing in Java

The DateTimeFormatter class provides three kinds of formatters to print a date/time value:

  • Predefined standard formatters (see Table 6.1)
  • Locale-specific formatters
  • Formatters with custom patterns

To use one of the standard formatters, simply call its format method:

String formatted = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(apolloniaunch);

// 1969-07-16T09:32:00-04:00M

The standard formatters are mostly intended for machine-readable time­stamps. To present dates and times to human readers, use a locale-specific formatter. There are four styles, SHORT, MEDIUM, LONG, and FULL, for both date and time—see Table 6.2.

The static methods ofLocatizedDate, ofLocatizedTime, and ofLocatizedDateTime create such a formatter. For example:

DateTimeFormatter formatter = DateTimeFormatter.ofLocatizedDateTime(FormatStyte.LONG);

String formatted = formatter.format(apoUo1Uaunch);

// July 16, 1969 9:32:00 AM EDT

These methods use the default locale. To change to a different locale, simply use the withLocate method.

formatted = formatter.withLocale(Locale.FRENCH).format(apollo11launch);

// 16 juillet 1969 09:32:00 EDT

The DayOfWeek and Month enumerations have methods getDisplayName for giving the names of weekdays and months in different locales and formats.

for (DayOfWeek w : DayOfWeek.values())

System.out.print(w.getDisplayName(TextStyle.SHORT, Locale.ENGLISH) + ” “);

// Prints Mon Tue Wed Thu Fri Sat Sun

See Chapter 7 for more information about locales.

Finally, you can roll your own date format by specifying a pattern. For example,

formatter = DateTimeFormatter.ofPattern(“E yyyy-MM-dd HH:mm”);

formats a date in the form Wed 1969-07-16 09:32. Each letter denotes a different time field, and the number of times the letter is repeated selects a particular format, according to rules that are arcane and seem to have organically grown over time. Table 6.3 shows the most useful pattern elements.

To parse a date/time value from a string, use one of the static parse methods. For example,

LocalDate churchsBirthday = LocalDate.parse(“1903-06-14”);

ZonedDateTime apollo11launch =

ZonedDateTime.parse(“1969-07-16 03:32:00-0400”,

DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ssxx”));

The first call uses the standard ISO_LOCAL_DATE formatter, the second one a custom formatter.

Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *