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
In general, a pattern consists of format specifiers, called pattern letters.
The pattern letters are case-sensitive.
Pattern | Description |
---|---|
a | AM/PM indicator |
d | Day in month |
E | Day in week |
h | Hour, 12-hour clock |
H | Hour, 24-hour clock |
M | Month |
m | Minutes |
s | Seconds |
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 }