Parse and format date time using LocalDateTime and other classes in Java

In this article you can find parse and format date-time examples.

If parse() method is called without passing a DateTimeFormatter object then the default ISO format for that date object is used.

E.g. In the case of LocalDateTime, the default format is DateTimeFormatter.ISO_LOCAL_DATE_TIME.
For ZonedDateTime, the default format is DateTimeFormatter.ISO_ZONED_DATE_TIME.

Most of the below methods are also applicable for other date classes such as OffsetDateTime, LocalDate, LocalTime.

Note: Calling toString() on a date object prints the date / time in default ISO format.

Instant date format is always DateTimeFormatter.ISO_INSTANT. There is no format method for Instant, although toString() can be used.

Example 1: LocalDateTime

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

class DateTimeExample
{
    public static void main ( String[] args )
    {
        LocalDateTime localDateTime1 = LocalDateTime.parse( “2021-02-18T06:17:10” );
        System.out.println( “LocalDateTime.parse: ” + localDateTime1 );

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern( “dd-MM-yyyy HH:mm:ss.SSS” );
        LocalDateTime localDateTime2 = LocalDateTime.parse( “02-01-2021 10:05:01.001”, dateTimeFormatter );
        System.out.println( “LocalDateTime.parse: ” + localDateTime2 );

        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern( “dd/MM/yyyy HH:mm:ss.SSS” );
        String formattedDate = localDateTime2.format( dateTimeFormatter1 );
        System.out.println( “LocalDateTime.format: ” + formattedDate );
    }
}

Output:

LocalDateTime.parse: 2021-02-18T06:17:10
LocalDateTime.parse: 2021-01-02T10:05:01.001
LocalDateTime.format: 02/01/2021 10:05:01.001

Example 2: ZonedDateTime

ZonedDateTime zonedDateTime = ZonedDateTime.parse( “2021-03-01T05:15:30.100-05:00” );
String formattedDateWithZone4 = zonedDateTime.format( DateTimeFormatter.ofPattern( “yyyy-MM-dd’T’HH:mm:ss.SSS z a E” ) );
System.out.println( “zonedDateTime: ” + zonedDateTime );
System.out.println( “ZonedDateTime.format: ” + formattedDateWithZone4 );

Output:

zonedDateTime: 2021-03-01T05:15:30.100-05:00
ZonedDateTime.format: 2021-03-01T05:15:30.100 -05:00 AM Mon

Example 3: Instant

Instant instant = Instant.parse( “2021-08-18T06:17:10.225Z” );
System.out.println( “Instant.parse: ” + instant );

Output:

Instant.parse: 2021-08-18T06:17:10.225Z

Leave a Comment

Your email address will not be published. Required fields are marked *