Java – Get Current Time

To get current time in Java

  1. Import LocalTime class from java.time package.
  2. Create LocalTime object by calling static method now() of LocalTime class. LocalTime.now() returns the current time from the system clock in the default time zone.
  3. Call toString() method on this LocalTime object. toString() method returns the current time as a String.

Example

In the following program, we shall use LocalTime class of java.time package and get the the current time.

Java Program

</>
Copy
import java.time.LocalTime;

public class Example {
	
	public static void main(String[] args) {
		LocalTime timeObj = LocalTime.now();
		String currentTime = timeObj.toString();
		System.out.println(currentTime);
	}

}

Output

09:45:07.711346

LocalTime.toString() method returns time in the format: HH:mm:ss.millis. We can format the time into any required pattern using DateTimeFormatter. Following are some of the tutorials, that provide examples to format Time.

Conclusion

In this Java Tutorial, we learned how to get current time using LocalTime class of java.time package, with example program.