Java - Date Time DateTimeFormatterBuilder Class


You can use DateTimeFormatterBuilder Class to create your own formatter.

DateTimeFormatterBuilder Class has a no-args constructor and many appendXxx() methods.

You create an instance of the class and call those appendXxx() methods to build the desired formatter.

Finally, call the toFomatter() method to get a DateTimeFormatter object.

The following code builds a DateTimeFormatter object to format a date in the format like "Christmas in YEAR is on WEEK_DAY":


import static java.time.format.TextStyle.FULL_STANDALONE;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.temporal.ChronoField.YEAR;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

public class Main {
  public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendLiteral("Christmas in ").appendValue(YEAR)
        .appendLiteral(" is on ").appendText(DAY_OF_WEEK, FULL_STANDALONE)
        .toFormatter();/*from  w  w w .j a va  2 s.c om*/
    LocalDate ld = LocalDate.of(2018, 12, 25);
    String str = ld.format(formatter);