Java format LocalDateTime value to String

In this Java core tutorial we learn how to format a LocalDateTime value to formatted String using the DateTimeFormatter class.

How to format date time using DateTimeFormatter in Java

FormatLocalDateTimeExample1.java

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

public class FormatLocalDateTimeExample1 {
    public static void main(String... args) {
        LocalDateTime localDateTime = LocalDateTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
        String formattedDateTime = localDateTime.format(dateTimeFormatter);

        System.out.println(formattedDateTime);
    }
}
The output is:
26-07-2021 00:37:16

FormatLocalDateTimeExample2.java

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

public class FormatLocalDateTimeExample2 {
    public static void main(String... args) {
        LocalDateTime localDateTime = LocalDateTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("E, MMM dd yyyy, hh:mm:ss a");
        String formattedDateTime = localDateTime.format(dateTimeFormatter);

        System.out.println(formattedDateTime);
    }
}
The output is:
Mon, Jul 26 2021, 12:37:35 AM

FormatLocalDateTimeExample3.java

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

public class FormatLocalDateTimeExample3 {
    public static void main(String... args) {
        LocalDateTime localDateTime = LocalDateTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDateTime = localDateTime.format(dateTimeFormatter);

        System.out.println(formattedDateTime);
    }
}
The output is:
2021-07-26

FormatLocalDateTimeExample4.java

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

public class FormatLocalDateTimeExample4 {
    public static void main(String... args) {
        LocalDateTime localDateTime = LocalDateTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
        String formattedDateTime = localDateTime.format(dateTimeFormatter);

        System.out.println(formattedDateTime);
    }
}
The output is:
26/07/21

FormatLocalDateTimeExample5.java

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

public class FormatLocalDateTimeExample5 {
    public static void main(String... args) {
        LocalDateTime localDateTime = LocalDateTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("E, MMM dd yyyy");
        String formattedDateTime = localDateTime.format(dateTimeFormatter);

        System.out.println(formattedDateTime);
    }
}
The output is:
Mon, Jul 26 2021

Happy Coding 😊