Java LocalTime

The Java LocalTime class is an immutable and thread-safe class that represents time with a default format of hh:mm:ss.zzz. The LocalTime class can be used to store time in the following format “05:45.30.123456789”.

How to use

This class does not handle or represent a date or time-zone. This class cannot represent an instant on the timeline without any additional information like offset or time-zone. Try the below-shown examples, it will print the date and time according to your system default zone. The time might be different if you run the code in our online Java Editor as the code is running on somewhere in the cloud.

Hour example

Following is the simple example that shows how you add/subtract hours in current time and print them.

import java.time.LocalTime;

public class LocalTimeHourExample {

    public static void main(String[] args) {

        // Get current time
        LocalTime localTime = LocalTime.now();
        System.out.println("Current time: " + localTime);

        // Add 5 hours to current time
        localTime = LocalTime.now().plusHours(5);
        System.out.println("Time after 5 hour: " + localTime);

        // Subtract 5 hours to current time
        localTime = LocalTime.now().minusHours(5);
        System.out.println("Time before 5 hour: " + localTime);
    }
}

Minute example

Following is the simple example that shows how you add/subtract minutes in the current time and print them.

import java.time.LocalTime;

public class LocalTimeMinuteExample {

    public static void main(String[] args) {

        // Get current time
        LocalTime localTime = LocalTime.now();
        System.out.println("Current time: " + localTime);

        // Add 10 minutes to current time
        localTime = LocalTime.now().plusMinutes(10);
        System.out.println("Time after 10 minutes: " + localTime);

        // Subtract 10 minutes to current time
        localTime = LocalTime.now().minusMinutes(10);
        System.out.println("Time before 10 minutes: " + localTime);
    }
}

Parsing example

The following example program shows how you can parse time from a given string.

import java.time.LocalTime;

public class LocalTimeParsingExample {

    public static void main(String[] args) {

        // Parse time from string
        LocalTime localTime = LocalTime.parse("05:10:00");
        System.out.println("Hour: " + localTime.getHour());
        System.out.println("Minute: " + localTime.getMinute());

        // Parse using of() function
        localTime = LocalTime.of(05, 10);
        System.out.println("Hour: " + localTime.getHour());
        System.out.println("Minute: " + localTime.getMinute());
    }
}