×

Java Programs

Java Practice

Java program to get individual components of the current time

Java example to demonstrate how to get individual components of the current time.
Submitted by Nidhi, on April 03, 2022

Problem statement

In this program, we will create an object of the LocalTime class and convert it into a string in a specified format. Then we will parse the time using the LocalTime class and its methods.

Source Code

The source code to get individual components of the current time is given below. The given program is compiled and executed successfully.

// Java program to get individual component 
// of current time

import java.util.*;
import java.time.*;
import java.text.*;

public class Main {
  public static void main(String[] args) {
    Date date = new Date();
    DateFormat dtFormat = new SimpleDateFormat("hh:mm:ss");

    final String strDate = dtFormat.format(date);
    LocalTime time = LocalTime.parse(strDate);

    int hh = time.getHour();
    int mm = time.getMinute();
    int ss = time.getSecond();

    System.out.printf("Current Utc Time: %02d:%02d:%02d", hh, mm, ss);
  }
}

Output

Current Utc Time: 05:32:15

Explanation

In the above program, we created a class Main that contains a static method main(). The main() method is the entry point for the program, here we created an object of the Date class and converted it into a string in a specified format. Then we parsed the components of the current time using methods of LocalTime class and printed the result.

Java Date and Time Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.