Java date format yyyy/mm/dd

 In this source code example, we will you how to format a Date into YYYY/MM/DD format in Java.

Java Format Date to YYYY/MM/DD

The below Java program demonstrates how to format Date into YYYY/MM/DD format:

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("yyyy/MM/dd");
        String d1 = formatterD1.format(date);
        
        System.out.println(d1);
        
        // yyyy-MM-dd HH:mm:ss
        SimpleDateFormat formatterD2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String d2 = formatterD2.format(date);
        
        System.out.println(d2);
        
        // E MMM yyyy HH:mm:ss.SSSZ
        SimpleDateFormat formatterD3 = new SimpleDateFormat("E MMM yyyy HH:mm:ss.SSSZ");
        String d3 = formatterD3.format(date);
        
        System.out.println(d3);
        
        System.out.println("\nStarting with JDK 8:");
        
        // yyyy-MM-dd
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatterLocalDate = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String ld1 = formatterLocalDate.format(localDate);

        // or shortly
        String ld2 = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        System.out.println(ld1);
        System.out.println(ld2);
    }
}

Output:

Before JDK 8:
2021/11/10
2021/11/10 16:38:20
Wed Nov 2021 16:38:20.048+0530

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

Comments