Few examples to show you how to format java.time.LocalDateTime in Java 8.

1. LocalDateTime + DateTimeFormatter

To format a LocalDateTime object, uses DateTimeFormatter

TestDate1.java

package com.favtuts.time;

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

public class TestLocalDateTime {

    public static void main(String[] args) {
        
        testLocalDateTimeToString();
    }
    

    private static void testLocalDateTimeToString() {
        // Get current date time
        LocalDateTime now = LocalDateTime.now();

        System.out.println("Before : " + now);          // 2022-05-25T15:57:20.601431

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String formatDateTime = now.format(formatter);  // 2022-05-25 15:57:20

        System.out.println("After  : " + formatDateTime);
    }

}

Output

Before : 2022-05-25T15:57:20.601431
After  : 2022-05-25 15:57:20

2. String -> LocalDateTime

Another example to convert a String to LocalDateTime

TestDate2.java

package com.favtuts.time;

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

public class TestLocalDateTime {

    public static void main(String[] args) {
               
        testStringToLocalDateTime();
    }

    private static void testStringToLocalDateTime() {

        String now = "2016-11-09 10:30";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        LocalDateTime formatDateTime = LocalDateTime.parse(now, formatter);

        System.out.println("Before : " + now);

        System.out.println("After : " + formatDateTime);

        System.out.println("After : " + formatDateTime.format(formatter));

    }
}

Output

Before : 2016-11-09 10:30
After : 2016-11-09T10:30
After : 2016-11-09 10:30

References

  1. DateTimeFormatter JavaDoc
  2. Java 8 – How to convert String to LocalDate

Leave a Reply

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