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
Calendar getInstance(): The Java Calendar getInstance() method gets a calendar using the current time zone and locale.
syntaxThe 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.
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:12Using 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
ExampleThe 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
java_date_time.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4