Java
Date Formatting
yyyy-MM-dd
Programming
Java Calendar

Calendar date to yyyy-MM-dd format in java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Java provides robust support for date and time manipulation primarily through the java.time package introduced in Java 8, known as the Java Date and Time API. Before Java 8, handling date and time was cumbersome due to various issues in the old java.util.Date and java.util.Calendar classes. The new API addresses these concerns and offers a cleaner and more comprehensive way to handle date and time. This article details how to convert a calendar date to the yyyy-MM-dd format in Java using the modern API.

Introduction to the java.time Package

Java's java.time package is centered around several core classes:

  • LocalDate: Represents a date without time-zone.
  • LocalTime: Represents a time without a time-zone.
  • LocalDateTime: Represents both date and time, without a time-zone.
  • ZonedDateTime: Represents a date and time with a time-zone.

For the purpose of formatting dates to yyyy-MM-dd, we primarily work with the LocalDate and the DateTimeFormatter classes. LocalDate captures only dates without associated time-of-day, making it ideal for formatting in a date-specific manner.

Example: Formatting a Date to yyyy-MM-dd

Let's illustrate the conversion of a calendar date to the yyyy-MM-dd format with a practical example using LocalDate.

java
1import java.time.LocalDate;
2import java.time.format.DateTimeFormatter;
3
4public class DateFormatterExample {
5    public static void main(String[] args) {
6        // Obtain current date
7        LocalDate currentDate = LocalDate.now();
8        
9        // Define the desired format using DateTimeFormatter
10        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
11        
12        // Format the LocalDate to a String
13        String formattedDate = currentDate.format(formatter);
14        
15        // Output the formatted date
16        System.out.println("Formatted Date: " + formattedDate);
17    }
18}

Explanation

  1. Obtaining the Current Date: We use LocalDate.now() to get the current date. This method does not account for time-zone which makes it suitable when time isn't a factor in operations.
  2. Defining the Formatter: DateTimeFormatter.ofPattern("yyyy-MM-dd") creates a formatter that specifies the needed output format. Note that yyyy represents the year, MM the month, and dd the day.
  3. Formatting the Date: The format() method converts the LocalDate into a String following the defined pattern.

Alternative Sources

If you are dealing with a java.util.Date instance, you can convert it to LocalDate as shown below:

java
1import java.util.Date;
2import java.time.LocalDate;
3import java.time.ZoneId;
4
5public class DateConverter {
6    public static void main(String[] args) {
7        // Assume date is provided
8        Date date = new Date();
9        
10        // Convert to LocalDate
11        LocalDate localDate = date.toInstant()
12                                   .atZone(ZoneId.systemDefault())
13                                   .toLocalDate();
14
15        // Use the previous formatter as shown above
16        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
17        String formattedDate = localDate.format(formatter);
18
19        // Output the formatted date
20        System.out.println("Formatted Date from util.Date: " + formattedDate);
21    }
22}

Conversion Table

StepDescription
LocalDate InitializationUse LocalDate.now() for the current date calculation.
Format Pattern DefinitionDefine using DateTimeFormatter.ofPattern("yyyy-MM-dd").
Formatting MethodUse .format(DateTimeFormatter) to convert LocalDate to a formatted string.
Date ConversionConvert java.util.Date to LocalDate using toInstant(), atZone(), and toLocalDate().

Additional Considerations

  • Time Zones: If you need to consider time-zones, ZonedDateTime is recommended.
  • Locale-Specific Formats: Date formatting can be locale-specific. The withLocale() method on DateTimeFormatter allows specifying a locale.
java
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                                                        .withLocale(Locale.FRANCE);
  • Thread Safety: DateTimeFormatter is immutable and thread-safe. This enables it to be safely used in a multi-threaded environment without external synchronization.

Using the java.time package drastically simplifies date-time operations in Java, paving the way for clearer and more maintainable code. Always prefer the java.time classes over legacy date-time classes for any new development.


Course illustration
Course illustration

All Rights Reserved.