How do I format date-time objects in Java 8?

In your Java application you want to format date-time objects using the new date and time API introduced in JDK 8. A solution to this problem is to use the java.time.format.DateTimeFormatter. The DateTimeFormatter class provides formatter for printing and parsing date-time objects.

With this class we can format the date-time objects using a predefined constants, there are many predefined ready to use formats, such as ISO_DATE, ISO_DATE_TIME. You can also use letters pattern to format the date-time objects, for instance using the dd MMMM yyyy. The formatter can format in localized style, in a long or medium style.

Let’s see an example below:

package org.kodejava.datetime;

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

public class DateTimeFormatterDemo {
    public static void main(String[] args) {
        // Get system current date and time.
        LocalDateTime time = LocalDateTime.now();

        // Get an instance of DateTimeFormatter and print a
        // formatted version of the system current date-time
        // using a predefined formatter.
        DateTimeFormatter format = DateTimeFormatter.ISO_DATE_TIME;
        System.out.printf("Time: %s%n", time.format(format));

        // Create a custom formatter and format the date-time
        // object.
        DateTimeFormatter customFormat =
                DateTimeFormatter.ofPattern("MMMM d, yyyy hh:mm a");
        System.out.printf("Time: %s%n", time.format(customFormat));

        // Create a custom formatter with locale and format the
        // date-time object.
        DateTimeFormatter localeFormat =
                DateTimeFormatter.ofPattern("d MMM yyyy HH:mm:ss",
                        Locale.FRENCH);
        System.out.printf("Time: %s%n", time.format(localeFormat));
    }
}

The results of the code above are:

Time: 2021-11-16T07:51:16.1247212
Time: November 16, 2021 07:51 AM
Time: 16 nov. 2021 07:51:16
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.