Java LocalTime

Jakob Jenkov
Last update: 2015-06-25

The LocalTime class in the Java 8 date time API represents a specific time of day without any time zone information. For instance, 10.00 AM . The LocalTime instance can be used to describe e.g. when school or work starts in different countries, where you are not interested in the UTC time, but the time in the respective countries. Of course you could also represent that as UTC time with a time zone, but you can also just use a LocalTime object without time zone information.

The LocalTime class is immutable, so all calculations on LocalTime objects return a new LocalTime instance.

Creating a LocalTime Object

You can create a LocalTime instance in several ways. The first way is to create a LocalTime instance that represents the exact time of now. Here is how that looks:

 LocalTime localTime = LocalTime.now();

Another way to create a LocalTime object is to create it from a specific amount of hours, minutes, seconds and nanoseconds. Here is how that looks:

LocalTime localTime2 = LocalTime.of(21, 30, 59, 11001);

There are also other versions of the of() method that only takes hours and minutes, or hours, minutes and seconds as parameters.

Accessing the Time of a LocalTime Object

You can access the hours, minutes, seconds and nanosecond of a LocalTime object using these methods:

  • getHour()
  • getMinute()
  • getSecond()
  • getNano()

LocalTime Calculations

The LocalTime class contains a set of methods that enable you to perform local time calculations. Some of these methods are:

  • plusHours()
  • plusMinutes()
  • plusSeconds()
  • plusNanos()
  • minusHours()
  • minusMinutes()
  • minusSeconds()
  • minusNanos()

Here is an example that shows how these methods work:

LocalTime localTime2 = LocalTime.of(21, 30, 59, 11001);

LocalTime localTimeLater   = localTime.plusHours(3);
LocalTime localTimeEarlier = localTime.minusHours(3);

The first line creates a LocalTime instance representing the time of day 21:30:50 and 11001 nanoseconds. The second line creates a LocalTime instance that represents a time 3 hours later. The third line creates a LocalTime instance that represents a time 3 hours earlier.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next