How do I use java.time.LocalTime class?

An instance of LocalTime class represent information about time. It doesn’t contain information about date. To create an instance of this class we can use the of() static factory method. There are two types of this method. The first one accept two arguments, hour and minute. The second type also accept the second as the arguments.

The code snippet below show you how to create an instance of LocalTime and how to obtain its values.

package org.kodejava.datetime;

import java.time.LocalTime;

public class LocalTimeDemo {
    public static void main(String[] args) {
        LocalTime time = LocalTime.of(15, 5, 30);

        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();

        System.out.println("hour = " + hour);
        System.out.println("minute = " + minute);
        System.out.println("second = " + second);
    }
}

To get the values from the LocalTime object we can use the getHour(), getMinute() and getSecond() methods to get hour, minute and second respectively.

Running this snippet result the following output:

hour = 15
minute = 5
second = 30

You can also use the get() method to read values represented by the LocalTime object. We call this method with the temporal field that we want to read. The following code snippet will give you the same result as the previous code, only this time we use the get() method.

int hour = time.get(ChronoField.HOUR_OF_DAY);       
int minute = time.get(ChronoField.MINUTE_OF_HOUR);  
int second = time.get(ChronoField.SECOND_OF_MINUTE);

System.out.println("hour   = " + hour);             
System.out.println("minute = " + minute);           
System.out.println("second = " + second);
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.