Java DateTimeFormatter

Jakob Jenkov
Last update: 2015-07-03

The Java DateTimeFormatter class is used to parse and format dates represented with the classes in the Java 8 date time API. The DateTimeFormatter is located in the java.time.format package so the fully qualified class name is java.time.format.DateTimeFormatter.

Predefined DateTimeFormatter Instances

The DateTimeFormatter class contains a set of predefined (constant) instances which can parse and format dates from standard date formats. This saves you the trouble of defining a date format for a DateTimeFormatter. The DateTimeFormatter class contains the following predefined instances:

BASIC_ISO_DATE

ISO_LOCAL_DATE
ISO_LOCAL_TIME
ISO_LOCAL_DATE_TIME

ISO_OFFSET_DATE
ISO_OFFSET_TIME
ISO_OFFSET_DATE_TIME

ISO_ZONED_DATE_TIME

ISO_INSTANT

ISO_DATE
ISO_TIME
ISO_DATE_TIME

ISO_ORDINAL_TIME
ISO_WEEK_DATE

RFC_1123_DATE_TIME

Each of these predefined DateTimeFormatter instances are preconfigured to format and parse dates to / from different formats. I will not explain all of these predefined DateTimeFormatter instances. You can read about them in the JavaDoc for the DateTimeFormatter class. But I will explain a few of them so you get an idea about what they do.

Formatting a Date

Once you have an instance of a DateTimeFormatter you can format a date using its format() method. Here is a DateTimeFormatter format() example:

DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;

String formattedDate = formatter.format(LocalDate.now());
System.out.println(formattedDate);

This example formats a LocalDate instance. An example output from this code could be:

20150703

This output represents the year 2015, month 07 (July) and day 03 (third).

Here is an example of formatting a ZonedDateTime instance:

DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;

String formattedZonedDate = formatter.format(ZonedDateTime.now());
System.out.println("formattedZonedDate = " + formattedZonedDate);

The output from this example would look like this:

20150703+0200

This output represents the year 2015, month 7 (July) and day 3 (third) in the time zone UTC+2 .

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next