DateTimeFormatterBuilder

Description

We can create custom date time formatter from DateTimeFormatterBuilder.

Example

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


import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
// w w  w .jav a 2 s.c  om
public class Main {

  public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendLiteral("New Year in ")
    .appendValue(ChronoField.YEAR)
    .appendLiteral(" is  on  ")
    .appendText(ChronoField.DAY_OF_WEEK,TextStyle.FULL_STANDALONE)
    .toFormatter(); 
    LocalDate ld  = LocalDate.of(2014, Month.JANUARY, 1); 
    String str = ld.format(formatter); 
    System.out.println(str);

  }
}

The code above generates the following result.

Example 2

We can create the same custom formatter using a pattern from DateTimeFormatterBuilder.


import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
/*w w w. j a v  a  2 s .c  o  m*/
public class Main {

  public static void main(String[] args) {
    LocalDate ld  = LocalDate.of(2014,Month.JANUARY,1);
    String pattern = "'New Year in'  yyyy  'is on' EEEE"; 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); 
    String str = ld.format(formatter);
    System.out.println(str); 

  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial