How to format LocalDateTime in Java 8

April 20, 2022 No comments Java8 LocalDateTime format time Java

1. Introduction

The LocalDateTime class from Java 8 is an immutable and thread-safe object that represents a date-time. In this article we will focus on how to format LocalDateTime using a custom pattern.

2. Using DateTimeFormatter class

The DateTimeFormatter is a class for printing and parsing date-time objects.

In the following example we use custom pattern to parse LocalDateTime using DateTimeFormatter class:

package com.frontbackend.datetime;

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

public class DateTimeFormatterTest {


    public static void main(String[] args) {
        // Get current datetime
        LocalDateTime currentDateTime = LocalDateTime.now();

        // Get DateTimeFormatter instance of custom pattern
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // Format datetime using DateTimeFormatter
        String formatDateTime = currentDateTime.format(formatter);

        System.out.println(formatDateTime);
    }
}

The program produces the following output:

2022-04-20 23:45

In this example:

  • first we created new instance of LocalDateTime - that represents current date time,
  • in the next step we use ofPattern(...) method on DateTimeFormatter to create custom formatter class,
  • finally, we format LocalDateTime using DateTimeFormatter.

We could also use inbuild DateTimeFormatter instances:

Formatter               Description                     Example    
-------                 -------                         -------
BASIC_ISO_DATE          Basic ISO date                  '20111203'
ISO_LOCAL_DATE          ISO Local Date                  '2011-12-03'
ISO_OFFSET_DATE         ISO Date with offset            '2011-12-03+01:00'
ISO_DATE                ISO Date with or without offset '2011-12-03+01:00'; '2011-12-03'
ISO_LOCAL_TIME          Time without offset             '10:15:30'
ISO_OFFSET_TIME         Time with offset                '10:15:30+01:00'
ISO_TIME                Time with or without offset     '10:15:30+01:00'; '10:15:30'
ISO_LOCAL_DATE_TIME     ISO Local Date and Time         '2011-12-03T10:15:30'
ISO_OFFSET_DATE_TIME    Date Time with Offset           '2011-12-03T10:15:30+01:00'
ISO_ZONED_DATE_TIME     Zoned Date Time                 '2011-12-03T10:15:30+01:00[Europe/Paris]'
ISO_DATE_TIME           Date and time with ZoneId       '2011-12-03T10:15:30+01:00[Europe/Paris]'
ISO_ORDINAL_DATE        Year and day of year            '2012-337'
ISO_WEEK_DATE           Year and Week                   '2012-W48-6'
ISO_INSTANT             Date and Time of an Instant     '2011-12-03T10:15:30Z'
RFC_1123_DATE_TIME      RFC 1123 / RFC 822              'Tue, 3 Jun 2008 11:05:30 GMT'

In the following example we are using inbuilt DateTimeFormatter instance:

package com.frontbackend.datetime;

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

public class DateTimeFormatterTest {


    public static void main(String[] args) {
        // Get current datetime
        LocalDateTime currentDateTime = LocalDateTime.now();

        // Format LocalDateTime using inbuilt formatters
        System.out.println(currentDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE));
        System.out.println(currentDateTime.format(DateTimeFormatter.ISO_LOCAL_TIME));
        System.out.println(currentDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        System.out.println(currentDateTime.format(DateTimeFormatter.ISO_WEEK_DATE));
        System.out.println(currentDateTime.format(DateTimeFormatter.ISO_ORDINAL_DATE));
        System.out.println(currentDateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
    }
}

Output:

2022-04-21
00:08:00.114
2022-04-21T00:08:00.114
2022-W16-4
2022-111
20220421

The list of common Patterns for Formatting and Parsing DateFormatter:

Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   G       era                         text              AD; Anno Domini; A
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   D       day-of-year                 number            189
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10

   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
   Y       week-based-year             year              1996; 96
   w       week-of-week-based-year     number            27
   W       week-of-month               number            4
   E       day-of-week                 text              Tue; Tuesday; T
   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
   F       week-of-month               number            3

   a       am-pm-of-day                text              PM
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-am-pm (1-24)  number            0

   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978
   A       milli-of-day                number            1234
   n       nano-of-second              number            987654321
   N       nano-of-day                 number            1234000000

Java example program that used custom patterns for formatting LocalDateTime:

package com.frontbackend.datetime;

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

public class DateTimeFormatterTest {


    public static void main(String[] args) {
        // Get current datetime
        LocalDateTime currentDateTime = LocalDateTime.now();

        // Format LocalDateTime using inbuilt formatters
        System.out.println(currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        System.out.println(currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        System.out.println(currentDateTime.format(DateTimeFormatter.ofPattern("EEE, MMM d, ''yy")));
        System.out.println(currentDateTime.format(DateTimeFormatter.ofPattern("h:mm a")));
        System.out.println(currentDateTime.format(DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss")));
    }
}

The output:

2022-04-21
00:17:39
Thu, Apr 21, '22
12:17 AM
Thu, 21 Apr 2022 00:17:39

3. Conclusion

In this article, we presented how to format LocalDateTime in Java 8. The DateTimeFormatter was designed for that job. Note that DateTimeFormatteris immutable and thread-safe. This object is perfect as a static final constant in a class where it will be used.

{{ message }}

{{ 'Comments are closed.' | trans }}