1. LocalTime
class
The LocalTime
class was created for cases where you need to work with time but without a date. For example, suppose you're writing an alarm clock application. You care about the time, but not the date.
The LocalTime
class is very similar to the LocalDate
class — its objects similarly cannot be changed after creation.
Getting the current time
To create a new LocalTime
object, you need to use the static now()
method. Example:
LocalTime time = LocalTime.now();
Where time
is a LocalTime
variable, and LocalTime.now()
is a call to the static now()
method of the LocalTime
class.
Example:
Code | Console output |
---|---|
|
|
The dot is followed by the current number of nanoseconds.
2. Getting a specific time
To get a specific time, you need to use the static of()
method. Example:
LocalTime time = LocalTime.of(hours, minutes, seconds, nanoseconds);
You pass in the hours, minutes, seconds and nanoseconds.
Example:
Code | Console output |
---|---|
|
|
By the way, there are two more variations of this method:
LocalTime time = LocalTime.of(hours, minutes, seconds);
and
LocalTime time = LocalTime.of(hours, minutes);
So you can use whichever is more convenient for you.
Getting a time based on the index of a second
You can also get the time by the index of a second in a day. To do this, we have the static ofSecondOfDay()
method:
LocalTime time = LocalTime.ofSecondOfDay(seconds);
Where seconds is the number of seconds since the beginning of the day.
Example:
Code | Console output |
---|---|
|
|
Yes, 10,000 seconds is a little less than three hours. It's all correct.
3. Getting elements of time
To get the value of a specific element of time from a LocalTime
object, we have these methods:
Method | Description |
---|---|
|
Returns the hours |
|
Returns the minutes |
|
Returns the seconds |
|
Returns the nanoseconds |
Example:
Code | Console output |
---|---|
|
|
4. Changing the time in a LocalTime
object
The LocalTime
class also has methods that let you work with time. The implementation of these methods is analogous to the methods of the LocalDate
class: they do not change the existing LocalTime
object, but instead return a new one with the desired data.
Here are the methods of the LocalTime
class:
Method | Description |
---|---|
|
Adds hours |
|
Adds minutes |
|
Adds seconds |
|
Adds nanoseconds |
|
Subtracts hours |
|
Subtracts minutes |
|
Subtracts seconds |
|
Subtracts nanoseconds |
Example:
Code | Console output |
---|---|
|
|
Note that in each case we get a new time that is relative to the original time
object. If you add 3600 seconds
to a time, then you add exactly 1hour
.
GO TO FULL VERSION