Q:

Java program to get individual components of the current time

belongs to collection: Java Date and Time Programs

0

Java program to get individual components of the current time

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program/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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Date and Time Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< Java program to compare time using equals() method...