Java how to use DateTimeFormatter

In this Java core tutorial we learn how to use the DateTimeFormatter class to format LocalDate, LocalTime or LocalDateTime value to formatted String.

How to format LocalDate value to formatted String

DateTimeFormatterExample1.java

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample1 {
    public static void main(String... args) {
        LocalDate localDate = LocalDate.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        String formattedDate = localDate.format(dateTimeFormatter);

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

How to format LocalTime value to formatted String

DateTimeFormatterExample2.java

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample2 {
    public static void main(String... args) {
        LocalTime localTime = LocalTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        String formattedTime = localTime.format(dateTimeFormatter);

        System.out.println(formattedTime);
    }
}
The output is:
00:41:11

How to format LocalDateTime value to formatted String

DateTimeFormatterExample3.java

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

public class DateTimeFormatterExample3 {
    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:41:25

Happy Coding 😊