Java DateTimeFormatter class

Introduction

DateTimeFormatter is in java.time.format.

To obtain a DateTimeFormatter instance, use one of its factory methods.

Three are shown here:

static DateTimeFormatter ofLocalizedDate(FormatStyle fmtDate) 
static DateTimeFormatter ofLocalizedTime(FormatStyle fmtTime) 
static DateTimeFormatter ofLocalizedDateTime(FormatStyle fmtDate, FormatStyle fmtTime ) 

FormatStyle is an enumeration that is packaged in java.time.format.

It defines the following constants:

FULL 
LONG 
MEDIUM 
SHORT 

Java DateTimeFormatter pattern

In general, a pattern consists of format specifiers, called pattern letters.

The pattern letters are case-sensitive.

Pattern Description
a AM/PM indicator
dDay in month
EDay in week
hHour, 12-hour clock
HHour, 24-hour clock
MMonth
mMinutes
sSeconds
y Year

Here is an example that uses DateTimeFormatter to display the current date and time:

// Demonstrate DateTimeFormatter. 
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class Main {
  public static void main(String args[]) {

    LocalDate curDate = LocalDate.now();
    System.out.println(curDate.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));

    LocalTime curTime = LocalTime.now();
    System.out.println(curTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)));
  }//from w  ww.  j a v a2s. c  o  m
}



PreviousNext

Related