Print current time in a day, month, and year format in Java

1. Introduction

Printing the current date in a specific format such as day, month, and year is a common task in many Java applications, from logging and reporting to user interfaces and time tracking. Java's java.time.format.DateTimeFormatter along with LocalDate provides a simple and efficient way to achieve this.

Key Points

1. LocalDate is used for obtaining the current date without time or timezone.

2. DateTimeFormatter allows for custom formatting of date objects.

3. The format "dd MMMM yyyy" translates to day in two digits, full month name, and four-digit year.

2. Program Steps

1. Import the necessary classes.

2. Obtain the current date.

3. Format the date according to the desired format.

3. Code Program

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

public class CurrentDatePrinter {

    public static void main(String[] args) {
        // Step 2: Obtain the current date
        LocalDate today = LocalDate.now();

        // Step 3: Define the desired date format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy");

        // Format the current date and print
        String formattedDate = today.format(formatter);
        System.out.println("Current date in day, month, and year format: " + formattedDate);
    }
}

Output:

Current date in day, month, and year format: 03 October 2023  // Output will vary based on the current date

Explanation:

1. LocalDate.now() is used to fetch the current date according to the system clock and default time-zone.

2. DateTimeFormatter.ofPattern("dd MMMM yyyy") creates a formatter based on the specified pattern. This pattern is "dd MMMM yyyy" which represents the day as two digits, the month as its full name, and the year as four digits.

3. The format method of LocalDate is used to format the date according to the specified formatter, which converts the date into a human-readable string matching the given pattern.


Comments