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);

    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap