Formatting time in a 24-hour format can be achieved by using the SimpleDateFormat class in Java. By specifying the correct pattern, we can display the time in a 24-hour format like "HH:mm:ss".
Displaying Hour in 24-hour FormatSimpleDateFormat: SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Date class: The Java Util Date class represents a specific instant in time, with millisecond precision.
SyntaxHere is the syntax of java.util.Date class constructor:
public class Date extends Object implements Serializable, Cloneable, Comparable<Date>
We will use the SimpleDateFormat class to display the hour in 24-hour format (HH). The format() method converts the current time into the desired format.
ExampleThe following example formats the time into 24 hour format (00:00-24:00) by using sdf.format(date) method of SimpleDateFormat class.
import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("h"); System.out.println("hour in h format : " + sdf.format(date)); } }Output
hour in h format : 8Displaying Time in 24-hour Format (hh:mm:ss)
We will formats the current time to display the hour, minute, and second in a 24-hour format using the HH:mm:ss pattern. It will output something like 06:04:26 based on the current system time.
ExampleThe following is another example of date and time
import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] argv) throws Exception { Date d = new Date(); SimpleDateFormat simpDate; simpDate = new SimpleDateFormat("hh:mm:ss"); System.out.println(simpDate.format(d)); } }Output
05:40:36
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