Write A Program To Display Current Date And Time In Java
Chapter:
Date and Time
Last Updated:
22-06-2023 13:57:57 UTC
Program:
/* ............... START ............... */
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTimeExample {
public static void main(String[] args) {
// Get the current date and time
LocalDateTime currentDateTime = LocalDateTime.now();
// Define the date and time format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// Format the current date and time using the defined format
String formattedDateTime = currentDateTime.format(formatter);
// Display the formatted current date and time
System.out.println("Current Date and Time: " + formattedDateTime);
}
}
/* ............... END ............... */
Output
Current Date and Time: 2023-06-22 12:34:56
Notes:
-
First, we import the necessary classes: LocalDateTime from the java.time package and DateTimeFormatter from the java.time.format package. These classes provide convenient methods to work with dates and times in Java.
- Next, we define a class called CurrentDateTimeExample. This class will contain our main method where the program execution starts.
- Inside the main method, we use the LocalDateTime.now() method to get the current date and time. This method retrieves the current date and time information from the system clock.
- We create a DateTimeFormatter object named formatter by calling the DateTimeFormatter.ofPattern() method. This method allows us to define a specific pattern for formatting the date and time.
- We specify the pattern "yyyy-MM-dd HH:mm:ss" in the ofPattern() method. This pattern represents the desired format for the date and time, where yyyy represents the year, MM represents the month, dd represents the day, HH represents the hour in 24-hour format, mm represents the minute, and ss represents the second.
- Now, we format the current date and time using the format() method of the LocalDateTime class. We pass the formatter object as an argument to the format() method to apply the desired formatting pattern.
- The result of the formatting operation is stored in a String variable called formattedDateTime.
- Finally, we use System.out.println() to display the formatted date and time on the console, along with some additional text.
- When you run this program, it will retrieve the current date and time, format it according to the specified pattern, and print the formatted date and time on the console.