
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Display Hour and Minute (current time) in Java
In this tutorial, we will learn how to display the current hour and minute by using the Calendar class or the SimpleDateFormat class in Java. The following are the ways to fetch and format the current time from the system
Using Calendar and Formatter
Using Calendar directly
Using Calendar and Formatter
Calendar getInstance(): The Java Calendar getInstance() method gets a calendar using the current time zone and locale.
syntax
The following is the syntax for Calendar getInstance()
public static Calendar getInstance()
The following are the steps to display hour and minute (current time)
Step 1: The Formatter object fmt is created to manage formatted output.
Step 2: A Calendar object cal is obtained using Calendar.getInstance(), which retrieves the current date and time.
Step 3: The format method of fmt is used to format the time. %tl formats the hour in 12-hour format, and %tM formats the minutes.
Example
The following example demonstrates how to display the hour and minute of that moment by using Calender.getInstance() of Calender class
import java.util.Calendar; import java.util.Formatter; public class MainClass { public static void main(String args[]) { Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); fmt = new Formatter(); fmt.format("%tl:%tM", cal, cal); System.out.println(fmt); } }
Output
09:12
Using Calendar directly
We directly retrieves the current hour and minute using the Calendar methods get(Calendar.HOUR_OF_DAY) and get(Calendar.MINUTE) and prints them
Example
The following is another example of hour and minute
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class HelloWorld { public static void main(String[] args) { Calendar now = Calendar.getInstance(); System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE)); } }
Output
5:31