Java 8 LocalTime

In this article, we will take a look at LocalTime in java, its meaning and how to create a time with hour, minute, second and nanosecond in java.

LocalTime is a new class added in java 8 in java.time package. It represents a time without any timezone information.

LocalTime is an immutable class. This means that once an instance of LocalTime is created, it cannot be modified.
LocalTime is also a final class. This means that you cannot extend and modify its functionality.
Creating LocalTime
A LocalTime object can be created using its static now() method as shown below

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

When current time is printed, the format is hh:MM:ss.SS. This is because LocalTime overrides toString() method which returns the time in this format.
Create LocalTime with hour & minute
LocalTime provides of() method which takes two integer arguments representing hour and minute. It returns a LocalTime with the values supplied. Example,

LocalTime date = LocalTime.of(21, 30);
System.out.println(date); // prints 21:30

Values for hour and minute must be valid.

Thus, LocalTime.of(25, 30) will throw

java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 – 23): 25

Create LocalTime with hour, minute, second
LocalTime has overloaded of() method which takes three integer arguments representing hour, minute and second. It returns a LocalTime with the values supplied. Example,

LocalTime date = LocalTime.of(21, 30, 55);
System.out.println(date); // prints 21:30:55

Similarly, there is an of() method with 4 arguments for hour, minute, second and nanosecond.
Create LocalTime from string
If you have a time in string form, it can be converted to a LocalTime using its parse() method as shown below

LocalTime time = LocalTime.parse("21:30"); 
System.out.println(time); // prints 21:30

There are two restrictions with parse():
1. Format of time string must be hh:mm:ss.SS. It is not necessary to provide all values. You need to provide at least hour and minutes.
2. Each component must be of 2 digits, that is, 1:30 is invalid. It should be 01:30.

If you want to parse time of different format, then use overloaded parse() method, which takes an object of DateTimeFormatter with custom format.
Below code is used to parse a date in hh:mm:ss format

DateTimeFormatter format = DateTimeFormatter.ofPattern("hh:mm:ss");
LocalTime date = LocalTime.parse("09:25:50",format); 
System.out.println(date); // prints 09:25:50

Get Fields from LocalTime
If you have a LocalTime object, then you can get fields of this time such as hour, minute, second and nanosecond, as shown below

LocalTime now = LocalTime.now();
System.out.println("Tine: " + now);
System.out.println("Hour: " + now.getHour());
System.out.println("Minute: " + now.getMinute());
System.out.println("Second: " + now.getSecond());
System.out.println("Nanosecond: " + now.getNano());

This prints

Time: 22:07:41.037867900
Hour: 22
Minute: 7
Second: 41
Nanosecond: 37867900

Get LocalTime for timezone
LocalTime has an overloaded now() method, which returns the current time in specified timezone. Timezone is supplied as an object of java.time.ZoneId. Example,

ZoneId euZone = ZoneId.of("Europe/London");
LocalTime euTime = LocalTime.now(euZone);
System.out.println("Current time in London: " + euTime);

ZoneId afZone = ZoneId.of("Europe/London");
LocalTime afTime = LocalTime.now(afZone); 
System.out.println("Current time in Nairobi: " + afTime);

This prints

Current time in London: 19:46:48.083263
Current time in Nairobi: 21:46:48.085578900

To create an object of ZoneId, we can use of() method of ZoneId supplying it the desired timezone as string.
Comparing LocalTimes
LocalTime contains methods that can be used to check if the times represented by two LocalTime objects fall before/after each other or they are same. Example,

LocalTime now = LocalTime.now();
// create a date for next year
LocalTime nextHour = LocalTime.of(now.getHour() + 1, 
          now.getMinute, now.getSecond());
System.out.println(nextHour.isAfter(now)); // true
System.out.println(now.isBefore(nextHour)); // false
System.out.println(now.compareTo(nextHour)); // -1

All methods are self-explanatory except compareTo(), which returns an integer value:
-1 : if the LocalTime on which it is called,  is before the argument object.
0 : if the LocalTime on which it is called, represents the same date as the argument object.
1 : if the LocalTime on which it is called, is after the argument object.
Creating LocalTime from another
In the last example, we created a LocalTime for next year by getting hour, minute, second and nanosecond from another LocalTime object and then used of() method with these values.

LocalTime provides methods to create a new LocalTime from an existing one by altering one of its fields. These methods are
1. withHour()
It takes an integer and returns a new LocalTime object with hour set to the supplied value.

2. withMinute()

It takes an integer and returns a new LocalTime object with minute set to the supplied value.

3. withSecond()

It takes an integer and returns a new LocalTime object with second set to the supplied value.

4. withNano()

It takes an integer and returns a new LocalTime object with nanosecond set to the supplied value.

All of these methods return a new LocalTime object. The object on which these methods are invoked remains unaltered. Example,

LocalTime now = LocalTime.now();
LocalTime nextHour = now.withHour(now.getHour()+1);
LocalTime nextMinute = now.withMinute(now.getMinute()+1);

Adding and subtracting in LocalTime
We can add or subtract hours, minutes or other components of time from a LocalTime using below methods

1. plusHours()
It takes a long value, adds it to the hours of LocalTime object and returns a new LocalTime.

2. plusMinutes()
It takes a long value, adds it to the minutes of LocalTime object and returns a new LocalTime.

3. plusSeconds()

It takes a long value, adds it to the seconds of LocalTime object and returns a new LocalTime.

4. plusNanos()

It takes a long value, adds it to the nanoseconds of LocalTime object and returns a new LocalTime.

5. plus()

It takes two arguments. First is a long value representing the amount and second is the unit to which it needs to be added.
Second argument is of type TemporalUnit. It is an interface which is implemented by ChronoUnit, an enum having fields for HOURS, MINUTES, SECONDS etc.

Example of these methods is given below,

LocalTime now = LocalTime.now();
LocalTime plusHours = now.plusHours(2);
LocalTime plusMinutes = now.plusMinutes(15);
LocalTime plusSeconds = now.plusSeconds(50);
// add 1 hour
LocalTime plus = now.plus(1, ChronoUnit.HOURS);
System.out.println("Time:" + now);
System.out.println("Time after adding hours: " 
            + plusHours);
System.out.println("Time after adding minutes: " 
            + plusMinutes);
System.out.println("Time after adding seconds: " 
            + plusSeconds);
System.out.println("Time after adding hours " + 
             "with plus method: " + plus);

Output is

Time: 21:13:34.641255900
Time after adding hours: 23:13:34.641255900
Time after adding minutes: 21:28:34.641255900
Time after adding seconds: 21:14:24.641255900
Time after adding hours with common method: 22:13:34.641255900

Each of the above methods creates a new LocalTime object. Original object remains unchanged.

Similary, LocalTime has corresponding methods to reduce time units. These methods begin with minus as shown below

LocalTime now = LocalTime.now();
LocalTime minusHours = now.minusHours(2);
LocalTime minusMinutes = now.minusMinutes(15);
LocalTime minusSeconds = now.minusSeconds(50);
// subtract 1 hour
LocalTime minus = now.minus(1, ChronoUnit.HOURS);
System.out.println("Time: " + now);
System.out.println("Time after subtracting hours: " 
                + minusHours);
System.out.println("Time after subtracting minutes: "
                + minusMinutes);
System.out.println("Time after subtracting seconds: " 
                + minusSeconds);
System.out.println("Time after subtracting hours " +
        " with minus method: " + minus);

This prints

Time: 21:16:52.391902200
Time after subtracting hours: 19:16:52.391902200
Time after subtracting minutes: 21:01:52.391902200
Time after subtracting seconds: 21:16:02.391902200
Time after subtracting hours with common method: 20:16:52.391902200

Each of these methods creates a new LocalTime object. Original object remains unchanged.

That is all on LocalTime in java 8.

We covered following aspects
1. How to create LocalTime set to current time with now() and with hour, minute, second and nanosecond using of() method and parsing a string time using parse() method.
2. Comparing two LocalTime objects using isBefore(), isAfter() and compareTo() methods.
3. How to create a LocalTime object from another object by modifying one of its fields.
4. Adding values to fields of a LocalTime object.

Hope the article was useful.