Java Program to create custom DateTime formatter

Java 8Object Oriented ProgrammingProgramming

To create custom DateTime formatter, use DateTimeFormatter. Let us first see for Time −

DateTimeFormatter dtFormat = new DateTimeFormatterBuilder()
.appendValue(ChronoField.HOUR_OF_DAY)
.appendLiteral(":")
.appendValue(ChronoField.MINUTE_OF_HOUR)
.appendLiteral(":")
.appendValue(ChronoField.SECOND_OF_MINUTE)
.toFormatter();

For Date −

dtFormat = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR)
.appendLiteral("/")
.appendValue(ChronoField.MONTH_OF_YEAR)
.appendLiteral("/")
.appendValue(ChronoField.DAY_OF_MONTH)
.toFormatter();

Example

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
public class Demo {
   public static void main(String[] args) {
      DateTimeFormatter dtFormat = new DateTimeFormatterBuilder()
      .appendValue(ChronoField.HOUR_OF_DAY)
      .appendLiteral(":")
      .appendValue(ChronoField.MINUTE_OF_HOUR)
      .appendLiteral(":")
      .appendValue(ChronoField.SECOND_OF_MINUTE)
      .toFormatter();
      System.out.println("Time = "+dtFormat.format(LocalDateTime.now()));
      dtFormat = new DateTimeFormatterBuilder()
      .appendValue(ChronoField.YEAR)
      .appendLiteral("/")
      .appendValue(ChronoField.MONTH_OF_YEAR)
      .appendLiteral("/")
      .appendValue(ChronoField.DAY_OF_MONTH)
      .toFormatter();
      System.out.println("Date = "+dtFormat.format(LocalDateTime.now()));
   }
}

Output

Time = 12:47:31
Date = 2019/4/19
raja
Published on 26-Apr-2019 10:24:55
Advertisements