Home >Java >javaTutorial >Java program to display current date and time
In this article, we will learn how to display the current date and time. Java does not have a built-in Date class, but we can import the java.time package to use the date and time API. This package contains many date and time classes.
Below is a demonstration of the same -
Assume our input is -
Run the program
The desired output is -
The current date and time is: 2022/03/17 23:43:17
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
Here, we bind all operations to 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)); } }
The required packages have been imported A LocalDateTime object has been defined The current date and time is: 2022/03/17 23:43:17
Here, we encapsulate operations into functions that demonstrate 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); } }
The required packages have been imported A LocalDateTime object has been defined The current date and time is: 2022/03/29 08:55:28
The above is the detailed content of Java program to display current date and time. For more information, please follow other related articles on the PHP Chinese website!