Java LocalTime now() Method Example - Get Current Time and Specific Time

This example shows how to get the current time and specific time using java.time.LocalTime.now() method.

The java.time.LocalTime class is an immutable class which represents a time without time-zone information.

Read more about LocalTime class with an example at https://www.javaguides.net/2018/08/java-8-localtime-class-api-guide.html.

Java LocalTime now() Method Example

LocalTime class provides below APIs to the current time and specific time object respectively.
  • static LocalTime now() - Obtains the current time from the system clock in the default time-zone.
  • static LocalTime now(Clock clock) - Obtains the current time from the specified clock.
  • static LocalTime now(ZoneId zone) - Obtains the current time from the system clock in the specified time-zone.
The following example shows how to get the current time and specific time using java.time.LocalTime.now() method:
import java.time.Clock;
import java.time.LocalTime;
import java.time.ZoneId;

/**
 * Program to demonstrate LocalTime Class APIs.
 * @author javaguides.net
 *
 */
public class LocalTimeExample {
 
    public static void main(String[] args) {
        createLocalTime();
    }
    private static void createLocalTime() {
       // Current Time
       LocalTime localTime = LocalTime.now();
       System.out.println(localTime);

       // Specific Time
       LocalTime localTime2 = LocalTime.of(4, 30, 45);
       System.out.println(localTime2);
  
       LocalTime localTime3 = LocalTime.now(Clock.systemDefaultZone());
       System.out.println(localTime3);
  
       LocalTime localTime4 = LocalTime.now(Clock.system(ZoneId.of("Indian/Cocos")));
       System.out.println(localTime4);
    }
}
Output:
17:38:35.349
04:30:45
17:38:35.350
18:38:35.350

Reference



Comments