How to create Date in yyyy-MM-dd format in Java

To create Date in yyyy-MM-dd format we will make use of,

  • the LocalDate from java.time package,

  • the DateTimeFormatter class from the java.time.format package.

Let's take a look at a few examples,


Example 1: From Current Date

package org.code2care.examples;

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

public class LocalDateFormattingyyyyMMddExample {

    private static final String YYYY_MM_DD = "yyyy-MM-dd";

    public static void main(String[] args) {

        LocalDate currentDate = LocalDate.now();

        DateTimeFormatter dataTimeFormatter = DateTimeFormatter.ofPattern(YYYY_MM_DD);
        String formattedDate = currentDate.format(dataTimeFormatter);
        System.out.println("Date Today: " + formattedDate);

    }
}
Output: 2023-07-03
Example - Java Date in yyyy-MM-dd format


Example 2: Formatting an existing Date as String

package org.code2care.examples;

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

public class LocalDateFormattingyyyyMMddExample2 {

    private static final String YYYY_MM_DD = "yyyy-MM-dd";

    public static void main(String[] args) {

        String dateString = "2023-07-03";
        LocalDate localDate = LocalDate.parse(dateString);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD);
        String formattedDate = localDate.format(formatter);
        System.out.println("Date: " + formattedDate);

    }
}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!