Java Data Type How to - Create custom Date time formatter








Question

We would like to know how to create custom Date time formatter.

Answer

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
/*from   w  w  w  . jav  a 2s .c o  m*/
public class Main {

  public static void main(String[] args) {
    DateTimeFormatter formatter =  new DateTimeFormatterBuilder()
      .appendValue(ChronoField.HOUR_OF_DAY)
      .appendLiteral(":")
      .appendValue(ChronoField.MINUTE_OF_HOUR)
      .toFormatter();

    
    System.out.println(formatter.format(LocalDateTime.now()));
  }
}

The code above generates the following result.