In this article, we will understand how to display current Date and Time. Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes.
Below is a demonstration of the same −
Suppose our input is −
Run the program
The desired output would be −
The current date and time is: 2022/03/17 23:43:17
Algorithm
Step 1 - START Step 2 - Declare an object of LocalDateTime namely date. Step 3 - Define the values. Step 4 - Define a date time format using DateTimeFormatter objects Step 5 - Display the date and time using a specific formats Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
System.out.println("A LocalDateTime object has been defined");
DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println("\nThe current date and time is: " +date_time.format(now));
}
}Output
The required packages have been imported A LocalDateTime object has been defined The first date format is:2022-03-29T08:55:00.214 The second date format is:29/03/2022 The third date format is:Tuesday, 29 Mar 2022
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Demo {
static void Date_time(DateTimeFormatter date_time){
LocalDateTime now = LocalDateTime.now();
System.out.println("\nThe current date and time is: " +date_time.format(now));
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
System.out.println("A LocalDateTime object has been defined");
DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
Date_time(date_time);
}
}Output
The required packages have been imported A LocalDateTime object has been defined The current date and time is: 2022/03/29 08:55:28