LocalTime Class In Java 8

The LocalTime class is new date time API in Java 8 that represents a specific time of day without any time zone information. A LocalTime is just a time in a day. For Example, If I want to meet my friend 1.00 PM tomorrow. This is what exactly a local time is. Off course I am not interested in the UTC time, but the time only. 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.

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

Creating a LocalTime Object:

There are many ways to create an Object of LocalTime class. First way is by calling now static method of LocalTime class, which represents the exact time of now.

We can also create local time by calling static of method by passing hour and minute as parameter.

There are other version of LocalTime.of() method which takes hours, minutes and seconds as parameters or hours, minutes, seconds and nanoseconds as parameters.

Accessing the Time of a LocalTime ClassObject

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

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

LocalTime Calculations:

We also have set of method to manipulate the time. Suppose my sleeping time is 11 PM at night and wake up time is 8 hours later in morning 7 AM.

Some of these methods are:

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

 

Leave a Reply

Your email address will not be published. Required fields are marked *