Java DateTimeFormatter ofPattern() Method
Example
Show the date and the time of a LocalDateTime with two patterns:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.of(2026, 1, 15, 14, 30);
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(myDateObj.format(format1));
System.out.println(myDateObj.format(format2));
}
}
Definition and Usage
The ofPattern() method creates a DateTimeFormatter from a pattern (a text where letters stand for parts of the date and time).
Common letters: yyyy (year), MM (month), dd (day), HH (hour, 0 to 23), mm (minute) and ss (second). MMM gives a short month name, like Jan, and E gives a short day name, like Thu.
Note: The letters are case-sensitive. MM is the month, but mm is the minute.
Syntax
One of the following:
public static DateTimeFormatter ofPattern(String pattern)
public static DateTimeFormatter ofPattern(String pattern, Locale locale)
Parameter Values
| Parameter | Description |
|---|---|
| pattern | Required. The pattern, for example "dd/MM/yyyy". |
| locale | Optional. The locale (a language and region setting) for month and day names, for example Locale.ENGLISH. If it is left out, the default locale of the computer is used. |
Technical Details
| Returns: | A new DateTimeFormatter object. |
|---|---|
| Throws: | IllegalArgumentException - if the pattern is not valid, for example if it has an unknown letter. |
Related Pages
❮ Date and Time Methods