In the field of development, Local Time is utilized for various purposes, such as it helps in retrieving the execution time, request, or response time. Moreover, using the Local Time we can schedule jobs or threads to perform multiple tasks in an orderly manner. The user can retrieve or modify the time fields to perform various operations using the methods provided by the “java.time.LocalTime” class. 

This guide explains the working of a “java.time.LocalTime” Class in Java.

What is java.time.LocalTime Class in Java?

The “java.time.LocalTime” class offers a large number of methods that perform unique operations over time. These operations include comparing times, modifying or truncating the time, adding or subtracting values from time fields, and many more. Some most important and usually used methods provided by the mentioned class are stated below along with their explanation in tabular format:

MethodExplanation
static LocalTime now()Retrieves the Current Time with the default time zone from the system.
Temporal adjustInto(Temporal temporal)Adjust the temporal Object to have the same time as the attached one. The Object to be adjusted is passed as an argument and according to which the change needs to be done invokes this method.
static LocalTime of( int hour, int minute, int second)Returns a local time by setting the provided parameters as values for time fields.
LocalDateTime atDate(LocalDate date)It merges the current or specified time with the provided date.
OffsetDateTime atOffset(ZoneOffset offset)Creates a new Time by merging the provided “offset” value
int compareTo(LocalTime other)It compares the provided time and returns “0” if both times are equal. If the time that is passed as an argument is greater then the “-1” value is returned and vice versa.
LocalTime minusMinutes(long minutesToSubtract)Returns a copy of the original time after subtracting the provided value from the “Minutes” time field
boolean equals(Object obj)Returns “true” if both provided times are equal else returns “false”.
String format(DateTimeFormatter format)Use the default or custom-defined format along with the “format()” method to set the formatting of time.
int get(TemporalField field)Retrieve the value of a specified time field like hours, minutes, seconds, etc.
int getHour()Retrieves the value of an “Hour” field from the attached time.
int getMinute()Retrieves the value of a “Minute” field from the targeted time.
int getNano()Returns the “NanoSecond” field value from the provided time. This field has the range of “0 to 999,999,999”
int getSecond()Extract the “Second” field value from the selected time.
int hashCode()Converts and returns the current or targeted time into “Hash Code” format.
boolean isAfter(LocalTime other)Check if the provided time is larger than the attached time or not.
boolean isBefore(LocalTime other)Identifies if the provided time is smaller than or before the attached time or not.
boolean isSupported(TemporalField field)Searches and checks whether the provided field is supported(valid). 
LocalTime minus(long subtractAmount, ChronoUnit unit)Returns the copy of an original time after subtracting the value from a specified time field like “Hours”.
LocalTime minusHours( long hoursToSubtract)Generates the copy of an original time after subtracting the value from the “Hours” time field.
LocalTime minusSeconds( long seconds)Generate the copy of an original time after subtracting the provided value from the “Seconds” time field.
static LocalTime parse(CharSequence data, DateTimeFormatter formatter)Extract time from the provided “data” using the specified “formatter”.
LocalTime plus(long amountToAdd, ChronoUnit value)Creates a copy of the original time after adding specified “values” to the targeted time field that can be an Hour, Minute, etc.
LocalTime plusHours(long hoursToAdd)Generates a copy of the original time after adding the provided value into the “Hour” field.
LocalTime plusMinutes(long minutesToAdd)Generates a copy of the original time after adding the provided value into the “Minute” field.
LocalTime plusSeconds(long seconds)Generates a copy of the original time after adding the provided value into the “Second” field.
<R> R query(TemporalQuery<R> query)Return data as a result for the specified “query” when applied over time.
String toString()Returns the targeted time in a String format.
long toNanoOfDay()Convert the time into “Nanoseconds” and return the result. It ranges from 0 to 24 * 60 * 60 * 1,000,000,000 – 1.
LocalTime truncatedTo(TemporalUnit unit)Return the copy of the original time after truncating or removing specified time fields.
int toSecondOfDay()Extracts the specified time into “Second” and it has the range of 0 to 24 * 60 * 60 – 1.
LocalTime with(TimeField field, long setValue)Creates the copy of a specified time field after setting the custom values for the specified time field.
LocalTime withSecond(int second)Generates a copy of the provided time after setting the custom value for the “Second” time field.
LocalTime withHour(int hour)Generates a copy of the targeted time after setting the custom value for the “Hour” time field.

Now, let’s implement some of the discussed methods in the Java program for better understanding.

Example 1: The now(), of(), equals(), and compareTo() Methods

In this example, the current and custom data are created using the “now()” and “of()” methods respectively. Then, both dates are compared using the “compareTo()” and “equals()” methods: 

import java.time.*;
public class LocaleTime{//Setting up Main() Method
public static void main(String args[]){// Storing current and provided Localtime
  LocalTime locTime = LocalTime.now();
  LocalTime locTime2 = LocalTime.of(8, 45, 53);

  int locTime3 = locTime.compareTo(locTime2);
  //positive value means locTime2 is greater than locTime and vice versa.
  boolean locTime4 = locTime.equals(locTime2);
  //False Means Both Times are Not Equal

  System.out.println("\n The Current Local Time is =>  "+ locTime );
  System.out.println("\n The Provided Local time is =>  "+ locTime2);
  System.out.println("\n Comparison Test For Both Local times =>  "+ locTime3);
  System.out.println("\n Equality Text Among Both Local Times =>  "+ locTime4);
}
}

In the above code block:

  • First, two local times are created having the system OS and user-provided data using the “now()” and “of()” methods.
  • Then, check which time is greater or lesser than the other one using the “compareTo()” method. Moreover, run the equality test by invoking the “equals()” method.

Output:

Example 2: The adjustInto(), atDate(), atOffset(), and format() Methods

In the below code snippet, the practical implementation and working are explained for the “adjustInto()”, “atDate()”, “atOffset()” methods. These methods adjust the “Date” and “Offset” parts with the targeted Time. Along with it, the formatting is performed to display only specific parts of data using the “format()” method:

import java.time.*;
import java.time.format.DateTimeFormatter;

public class LocaleTime{
public static void main(String args[]){
  // Getting the Current and Provided Local Time
  LocalTime locTime = LocalTime.now();
  LocalTime locTime2 = LocalTime.of(8, 45, 53);

  //Adding Offset of "2" Hours
  OffsetTime locTime3 = locTime.atOffset(ZoneOffset.ofHours(2));

  //Getting Current Date and Adding that Date With Provided Time
  LocalDate locDate = LocalDate.now();
  LocalDateTime locDateTime1 = locTime2.atDate(locDate);

  //Getting Current Zoned Date and Adding that Date With Provided Time
  ZonedDateTime zonedLocDate = ZonedDateTime.now();
  ZonedDateTime locDateTime2 = (ZonedDateTime)locTime2.adjustInto(zonedLocDate);

  //Formatting the Date to Display Only Time Part With Offset
  DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME;
  String formatted = formatter.format(locDateTime2);

  System.out.println("  The Current Local Time is =>  " + locTime );
  System.out.println("\n  The Provided Local Time is =>  " + locTime2);
  System.out.println("\n\n 1) Adding Offset Value to Current Local Time =>  " + locTime3);
  System.out.println("\n\tCurrent Date: " + locDate);
  System.out.println("\n 2) Adding Current Date to the Provided Local Time =>  " + locDateTime1);
  System.out.println("\n\tZoned Current Date: " + zonedLocDate);
  System.out.println("\n 3) Inserting Zoned Date to Local Times =>  " + locDateTime2);
  System.out.println("\n 4) Formated the Zoned Date Time to Display Only Time Part=>  " + formatted);
}
}

The working of the above code is as follows:

  • First, create two Local Dates from the System and user-provided data using the “now()” and “of()” methods.
  • Next, add an offset for the “Hours” time field using the “atOffset(ZoneOffset.ofHours())” method. Add this offset with the already retrieved current Time and store the result in a “lacTime3” variable.
  • Then, apply the “now()” method with the “LocalDate” and “ZonedDateTime” classes to retrieve the current Local and Zoned Dates. Now, add the Local and Zoned Dates with the required time using the “adjustInto()” and “addDate()” methods respectively.
  • Now, set a date and time formatter using the “DateTimeFormatter” class. Also, apply this formatting to the retrieved Zoned Date and Time using the “format()” method.
  • Lastly, display all results on the console for verification purposes.

Output:

Example 3: Retrieving, Truncating, Modifying, and Setting the Time Fields in Java

In this example, multiple methods are implemented to perform various operations like retrieving specific or truncated parts of time fields. Then, single or multiple time fields are modified by addition or subtraction of a specified value. Let’s proceed:

import java.time.*;
import java.time.temporal.ChronoUnit;
public class LocaleTime{

public static void main(String args[]){
  // Getting the Current Local Date and Time
  LocalTime locTime = LocalTime.now();
  System.out.println("Current Local Time is =>  "+ locTime );
  LocalDateTime locDate = LocalDateTime.now();
  System.out.println("Current Local Date is =>  "+ locDate );

  //Retrieving Single Field Values of Current Local Time
  int hourValue = locTime.getHour();
  int minValue = locTime.getMinute();
  int secValue = locTime.getSecond();
  System.out.println("\n Retrieved Value of Hour field is: =>  " + hourValue);
  System.out.println("\n Retrieved Value of Minute field is: =>  " + minValue);
  System.out.println("\n Retrieved Value of Second field is: =>  " + secValue);
 
  //Truncating to Display the Local Date Till the Minute Field
  LocalDateTime selectedPart = locDate.truncatedTo(ChronoUnit.MINUTES);
  System.out.println("\n Displaying Only Hour and Minute Fields =>  " + selectedPart);

  //Subtracting Hours Field Value
  LocalTime subHours = locTime.minusHours(5);
  System.out.println("\n  After Subtracting '5' Hours From the Current Local Time =>  " + subHours);
 
  //Adding Minutes Field Value
  LocalTime addMinutes = locTime.plusMinutes(5);
  System.out.println("\n  After adding '5' Minutes to the Local Time =>  " + addMinutes);
 
  //Setting Hour Field Value
  LocalTime setHours = locTime.withHour(4);
  System.out.println("\n  Setting '4' as a Value for Current Local Time 'Hour' Field =>  " + setHours);
 
  //Displaying HashCode for Current Local Date
  int hashValue = locTime.hashCode();
  System.out.println("\n  The Hash Code for Current Local Time is =>  " + hashValue);
 
  //Displaying Current Local Date in Nanoseconds
  long nanoSecValue = locTime.toNanoOfDay();
  System.out.println("\n  Converted Current Local Time into Nano-Seconds =>  " + nanoSecValue);
}
}

The internal working of the above code is as follows:

  • First, invoke the “now()” method over the “LocalTime” and “LocalDateTime” classes to get the current Local Time and Date. Also, store the result in the “LocTime” and “LocDate” variables.
  • Next, call the “getHour()”, “getMinute()”, and “getSecond()” methods over the “locTime” variable. This calling returns a value for the “Hour”, “Minute”, and “Second” fields of the Local Time “locTime”.
  • Then, apply the “truncatedTo()” method with the argument of “ChronoUnit.MINUTES”. This method truncates the Local Time and returns value till the “Minute” field i.e. “Hours” and “Minutes”.
  • Now, apply the “minusHours()” and “plusMinutes()” methods to subtract and add the values for the “Hours” and “Minutes” fields respectively. The values to be subtracted and added are passed as an argument.
  • After that, utilize the “withHour()” method to set the value for the Time “Hours” field.
  • Lastly, apply the “hashCode()” and “toNanoOfDay()” methods to convert the time into hash codes and nanosecond format.

Output:

That’s all about the “java.time.LocalTime” Class in Java.

Conclusion

The “java.time.LocalTime” class of Java consists of multiple methods; each method allows users to interact with Time and its fields. These methods allow users to extract, modify, compare, format a portion or entire Time, and many more as per requirements. Moreover, the users can retrieve hash codes, and add Local or Zoned dates with the desired time. This guide has explained the “java.time.LocalTime” class methods with the help of practical implementation.