Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

DateTimeFormatter.ofPattern: a date-time pattern with Locale.ENGLISH

Build a formatter for `yyyy-MM-dd HH:mm z` with an explicit `Locale.ENGLISH`, and learn where the time zone in the output comes from.

Version: Java SE 21

Syntax

import java.time.format.DateTimeFormatter;
import java.util.Locale;

DateTimeFormatter.ofPattern(String pattern)
DateTimeFormatter.ofPattern(String pattern, Locale locale)

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z", Locale.ENGLISH)

The static method DateTimeFormatter.ofPattern in java.time.format creates an immutable, thread-safe formatter you can reuse for formatting and parsing. ofPattern(String) takes the default locale for Locale.Category.FORMAT; ofPattern(String, Locale) uses the locale you pass, such as Locale.ENGLISH. Both overloads throw IllegalArgumentException when you create a formatter with an invalid pattern. Both default to SMART resolution when parsing.

Pattern letters are case-sensitive. In yyyy-MM-dd HH:mm z, yyyy is the year of the era with at least four digits. MM and dd are the month and day of the month; HH and mm are the hour (00–23) and minute. Those four fields are zero-padded to two digits. uuuu instead represents the proleptic year, which includes year 0.

When formatting, a single z prints a short zone name and accounts for daylight saving time when it can determine whether it applies. Locale.ENGLISH chooses the language for that text, not the zone. Neither overload sets a zone override: a ZonedDateTime supplies the zone, but a LocalDateTime alone does not. Names for regional zones can vary with the runtime's locale data and need not be unique. For a fixed ZoneOffset, z prints the offset ID instead of a name.

Examples

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z", Locale.ENGLISH);
        ZonedDateTime dateTime =
                ZonedDateTime.of(2024, 2, 9, 7, 5, 0, 0, ZoneOffset.ofHours(2));
        System.out.println(formatter.format(dateTime));
    }
}

Result

2024-02-09 07:05 +02:00

The output `2024-02-09 07:05 +02:00` comes from an explicit date, time, and fixed offset. `+02:00` is the offset ID, not an English zone name. The example uses neither the system clock nor the default zone or locale.

Related lessons

  • Java · Lesson 59 · Intermediate · Version: 2

Sources