In the previous article, we have discussed about Java Program to Display Current Month in the (MMM) Format
In this article we are going to see how to display current date and time in Java along with suitable examples.
Java Program to Display Current Date and Time
Let’s see the program
Method-1:
The java.util.Formatter
class provides inbuild “.format()
” methods to format the hour and minute in java.
The java.util.Calendar
class provides an inbuild method “.getInstance()
” method to get the instant date-time-month from the system calendar Where %tc
represent current date and time.
Approach:
- Create object of Formatter as ‘f’
- Declare a variable ‘cal’ of type Calendar and initialize it to get the system date-time using Calendar.getInstance() method.
- Using inbuild method of formatter class .format(“%tl:%tM”, calendar, calendar) we can get the current time in hour minute format.
- Print the result.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create object of Formatter as ‘f’ Formatter f = new Formatter(); // Declare a variable ‘cal’ of type Calendar //and initialize it to get the system date-time using Calender.getInstance() method Calendar cal = Calendar.getInstance(); // using inbuild method of formatter class .format("%tc", cal) we can get the current date and time format f.format("%tc", cal); //print the result System.out.println("The current date and time is: "+f); } }
Output: The current date and time is: Sun Jun 26 07:39:14 GMT 2022
Method-2:
Approach:
- Create an object of Date class which takes the system date and time.
- Print the result using inbuild method of Date class as ‘
date.toString()
’ to get the current date and time.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an object of Date class which takes the system date and time Date date = new Date(); //Print the result using inbuild method of Date class as ‘date.toString()’ to get the current date and time. System.out.println("The current date and time is: "+date.toString()); } }
Output: The current date and time is: Sun Jun 26 07:43:18 GMT 2022
Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language.
Related Java Programs: