Java Reference
In-Depth Information
DateTimeFormatter class also supports a static factory method that lets you create a formatter
from a specific pattern, as shown in the next listing.
Listing 12.10. Creating a DateTimeFormatter from a pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date1 = LocalDate.of(2014, 3, 18);
String formattedDate = date1.format(formatter);
LocalDate date2 = LocalDate.parse(formattedDate, formatter);
Here the LocalDate's format method produces a String representing the date with the requested
pattern. Next, the static parse method re-creates the same date by parsing the generated String
using the same formatter. The ofPattern method also has an overloaded version allowing you to
create a formatter for a given Locale, as shown in the following listing.
Listing 12.11. Creating a localized DateTimeFormatter
DateTimeFormatter italianFormatter =
DateTimeFormatter.ofPattern("d. MMMM yyyy", Locale.ITALIAN);
LocalDate date1 = LocalDate.of(2014, 3, 18);
String formattedDate = date.format(italianFormatter); // 18. marzo 2014
LocalDate date2 = LocalDate.parse(formattedDate, italianFormatter);
Finally, in case you need even more control, the DateTimeFormatterBuilder class lets you define
complex formatters step by step using meaningful methods. In addition, it provides you with the
ability to have case-insensitive parsing, lenient parsing (allowing the parser to use heuristics to
interpret inputs that don't precisely match the specified format), padding, and optional sections
of the formatter. For example, you can programmatically build the same italianFormatter we
used in listing 12.11 through the DateTimeFormatterBuilder as follows.
Listing 12.12. Building a DateTimeFormatter
DateTimeFormatter italianFormatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_MONTH)
.appendLiteral(". ")
.appendText(ChronoField.MONTH_OF_YEAR)
.appendLiteral(" ")
.appendText(ChronoField.YEAR)
.parseCaseInsensitive()
 
Search WWH ::




Custom Search