Write a Java Program to Get individual components of the current time


This Java program demonstrates how to get the current UTC time in hours, minutes, and seconds using the Date, DateFormat, LocalTime, and SimpleDateFormat classes.

  • The program first creates a new instance of Date using the default constructor, which returns a Date object set to the current date and time. The program then creates a new instance of DateFormat using the SimpleDateFormat class, which is used to format the date and time into a string in the desired format. In this case, the format is set to "hh:mm:ss", which specifies the hour, minute, and second components of the time.
  • The program then uses the format() method of the DateFormat class to format the current date and time into a string. The resulting string is then parsed into a LocalTime object using the parse() method of the LocalTime class.
  • Next, the program extracts the hour, minute, and second components of the LocalTime object using the getHour(), getMinute(), and getSecond() methods, respectively.
  • Finally, the program prints the current UTC time in the desired format using the printf() method of the PrintStream class.

Overall, this program provides a simple example of how to get the current UTC time in hours, minutes, and seconds using the Date, DateFormat, LocalTime, and SimpleDateFormat classes in Java. However, it is worth noting that the Date and DateFormat classes have been replaced by the newer java.time API in Java 8 and later versions, which provides more flexible and robust date and time handling capabilities.

Source Code

import java.util.*;
import java.time.*;
import java.text.*;
public class Individual_Component 
{
	public static void main(String[] args)
	{
		Date dt = new Date();
		DateFormat dtFormat = new SimpleDateFormat("hh:mm:ss");
 
		final String str_dt = dtFormat.format(dt);
		LocalTime time = LocalTime.parse(str_dt);
 
		int h = time.getHour();
		int m = time.getMinute();
		int s = time.getSecond();
 
		System.out.printf("Current Utc Time : %02d:%02d:%02d", h, m, s);
	}
}

Output

Current Utc Time : 02:20:31

Example Programs