Java format LocalDate to dd-MM-yyyy

In this source code example, we will you how to format a LocalDate into dd-MM-yyyy format in Java.

Java format LocalDate to dd-MM-yyyy


import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Main {

    public static void main(String[] args) {

        System.out.println("Before JDK 8:");
        // yyyy-MM-dd
        Date date = new Date();
        
        SimpleDateFormat formatterD1 = new SimpleDateFormat("dd-MM-yyyy");
        String d1 = formatterD1.format(date);
        System.out.println(d1);
        
        System.out.println("\nStarting with JDK 8:");
        
        // yyyy-MM-dd
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatterLocalDate = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        String ld1 = formatterLocalDate.format(localDate);
        System.out.println(ld1);
        
        // or shortly
        String ld2 = LocalDate.now().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
        System.out.println(ld2);
    }
}

Output:

Before JDK 8:
10-11-2021

Starting with JDK 8:
10-11-2021
10-11-2021


Comments