Java 8 – LocalTime with method details and examples

In this article, we will discuss about newly introduced LocalTime class in Java 1.8 version for dealing with date and time in program with ease and convenience.

Prior to introducing LocalDate and LocalTime in Java 1.8 version, we have to deal with java.util.Date, java.util.Calendar, java.sql.Timestamp, java.sql.Time, java.util.TimeZone for date/time handling in Java which isn’t easy & straight-forward and there are few issues as mentioned below,

  • Thread-safety :- Existing Date/Time classes and its methods aren’t thread-safe and hence it’s not convenient to handle in concurrent/parallel environment
  • Not so-easy API design :- Existing Date/Time classes’ methods aren’t convenient to use in day-to-day programmer’s coding or development
  • Time-zone settings :- Developers or Programmer’s life becomes difficult while dealing with time zone settings in programs

Let’s move forward and discuss about java.time.LocalTime introduced in Java 1.8 version

1. LocalTime :

  • There are 3 ways to get/form a LocalTime,
    1. First is to get current system time using static factory method now()
    2. Second is to form a LocalTime using static factory method of() passing hour, minute, second and nano information
    3. Third and final is to parse time in String-form to LocalTime using static factory method parse()
  • The fully qualified package/class name of LocalTime is java.time.LocalTime i.e.; LocalTime is present under java.time package
  • Class declaration for LocalTime is as follows,
package java.time;

public final class LocalTime
        implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable {
}

2. LocalTime methods or APIs :

Important LocalTime method details,

  • now() – get the current time from the system clock in the default time-zone
  • of() – get an instance of LocalTime passing either hour/minute or hour/minute/second or hour/minute/second/nano (there are 3 variants)
  • parse() – get an instance of LocalTime from a text string in either hour:minute or hour:minute:second or hour:minute:second.nano formats
  • getHour() – get the hour-of-day field from LocalTime
  • getMinute() – get the minute-of-hour field from LocalTime
  • getSecond() – get the  second-of-minute field from LocalTime
  • getNano() – get the nano-of-second field from LocalTime
  • plusNanos() – Returns a copy of invoking LocalTime with the specified number of nanoseconds added
  • plusSeconds() – Returns a copy of invoking LocalTime with the specified number of seconds added
  • plusMinutes() – Returns a copy of invoking LocalTime with the specified number of minutes added
  • plusHours() – Returns a copy of invoking LocalTime with the specified number of hours added
  • minusNanos() – Returns a copy of invoking LocalTime with the specified number of nanoseconds subtracted
  • minusSeconds() – Returns a copy of invoking LocalTime with the specified number of seconds subtracted
  • minusMinutes() – Returns a copy of invoking LocalTime with the specified number of minutes subtracted
  • minusHours() – Returns a copy of invoking LocalTime with the specified number of hours subtracted
  • format() – Formats invoking LocalTime using the specified date formatter
  • withHour() – Returns a copy of this LocalTime with the hour-of-day altered
  • withMinute() – Returns a copy of this LocalTime with the minute-of-hour altered
  • withSecond() – Returns a copy of this LocalTime with the second-of-minute altered
  • withNano() – Returns a copy of this LocalTime with the nano-of-second altered
  • isAfter(LocalTime) – Checks if the invoking LocalTime is after the specified LocalTime
  • isBefore(LocalTime) – Checks if the invoking LocalTime is before the specified LocalTime
  • atDate(LocalDate) – Combines invoking LocalTime with a passed LocalDate to create a LocalDateTime
  • atOffset(ZoneOffset) – Combines invoking LocalTime with an offset to create an OffsetTime
  • toSecondOfDay() – This method converts LocalTime into Seconds or seconds of day ranging from 0 seconds to 86399 seconds
  • ofSecondOfDay(long) – This method converts given seconds in long format to LocalTime in the default (HH:mm:ss) format
  • toNanoOfDay() – This method converts LocalTime into Nanoseconds or nano of day ranging from 0 nanoseconds to 86399999999999 nanoseconds
  • ofNanoOfDay() – This method converts given nanoseconds in long format to LocalTime in the default (HH:mm:ss.nnn) format
  • isSupported(TemporalField) – checks if the specified field is supported by invoking LocalTime and returns boolean value true/false
  • isSupported((TemporalUnit) – checks if the specified unit is supported by invoking LocalTime and returns boolean value true/false

3. LocalTime examples :

  1. LocalTime.now() – get current time from system clock
  2. LocalTime.of() – form LocalTime passing Hour, Minute, Second and Nano fields
  3. LocalTime.parse() – parse the time in String-form to LocalTime
  4. Adding nano, second, minute and hour to LocalTime using plusNanos(), plusSeconds(), plusMinutes() and plusHours() methods respectively
  5. Subtracting nano, second, minute and hour from LocalTime using minusNanos(), minusSeconds(), minusMinutes() and minusHours() methods respectively
  6. Formatting LocalTime in different formats using DateTimeFormatter class
  7. Altering nano, second, minute and hour fields with LocalTime using withNano(), withSecond(), withMinute() and withHour() methods respectively
  8. Check LocalTime is Before/After another LocalTime using below methods,
    • isBefore(LocalTime) – checks if the invoking LocalTime is before the specified LocalTime
    • isAfter(LocalTime) – checks if the invoking LocalTime is after the specified LocalTime
  9. Convert LocalTime to LocalDateTime/OffsetTime
  10. Convert LocalTime to number of Seconds and vice-versa
  11. Convert LocalTime to number of Nanoseconds and vice-versa
  12. Check Temporal Field supported by LocalTime using isSupported() method
  13. Check Temporal Unit supported by LocalTime using isSupported() method

3.1 LocalTime.now() method – get Current System Time

  • LocalTime.now() method helps to get current system time which will be in the ISO_LOCAL_TIME or HH:mm:ss.nnn format
  • We can get hour, minute, second and nano field/part from LocalTime using different methods mentioned above and then we can form our own format as required like for example HH-mm-ss-nnn
  • Read Java 8 – How to get Hour, Minute and Second fields from LocalTime ? for more details and examples

LocalTimeExampleUsingNowMethod.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class LocalTimeExampleUsingNowMethod {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException {

		// 1. get current system time
		LocalTime localTime = LocalTime.now();
		System.out.println("Current system time is = " + localTime);


		// 1.1 get HOURs value from current system time
		int hours = localTime.getHour();
		System.out.println("\n1. Hour is : " + hours);


		// 1.2 get MINUTEs value from current system time
		int minutes = localTime.getMinute();
		System.out.println("2. Minutes is : " + minutes);


		// 1.3 get SECONDs value from current system time
		int seconds = localTime.getSecond();
		System.out.println("3. Seconds is : " + seconds);


		// 1.4 get NANO SECONDs value from current system time
		int nano = localTime.getNano();
		System.out.print("4. Nano Seconds is : " + nano);
	}
}

Output:

Current system time is = 17:17:04.199256100

1. Hour is : 17
2. Minutes is : 17
3. Seconds is : 4
4. Nano Seconds is : 199256100

3.2 LocalTime.of() method – form Time

  • Passing hour, minute, second and nano field/part to LocalTime.of() method returns LocalTime which will be in the HH:mm:ss.nnn format
  • We can extract different fields like hour, minute, second and nano from LocalTime and then form our own format as required like for example HH.mm.ss.nnn
  • Note: There are 3 variants of LocalTime.of() method
  • Read Java 8 – How to form LocalTime passing Hour, Minute and Second fields ? for more details and examples

LocalTimeExampleUsingOfMethod.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class LocalTimeExampleUsingOfMethod {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException {

		// 1. First variant passing hour, minute, second and nano
		LocalTime time1 = LocalTime.of(11, 45, 37, 987000000);
		System.out.println("LocalTime using 1st variant is = " + time1);


		// 1.1 get HOUR value from LocalTime
		int hours = time1.getHour();
		System.out.println("\n1. Hour is : " + hours);


		// 1.2 get MINUTE value from LocalTime
		int minutes = time1.getMinute();
		System.out.println("2. Minutes is : " + minutes);


		// 1.3 get SECOND value from LocalTime
		int seconds = time1.getSecond();
		System.out.println("3. Seconds is : " + seconds);


		// 1.4 get NANO SECONDs value from LocalTime
		int nano = time1.getNano();
		System.out.println("4. Nano Seconds is : " + nano);



		// 2. Second variant passing hour, minute and second
		LocalTime time2 = LocalTime.of(7, 18, 23);
		System.out.println("\nLocalTime using 2nd variant is = " + time2);


		// 2.1 get HOUR value from LocalTime
		System.out.println("\n1. Hour is : " + time2.getHour());


		// 2.2 get MINUTE value from LocalTime
		System.out.println("2. Minutes is : " + time2.getMinute());


		// 2.3 get SECOND value from LocalTime
		System.out.println("3. Seconds is : " + time2.getSecond());



		// 3. Third variant passing hour and minute only
		LocalTime time3 = LocalTime.of(5, 31);
		System.out.println("\nLocalTime using 3rd variant is = " + time3);


		// 3.1 get HOUR value from LocalTime
		System.out.println("\n1. Hour is : " + time3.getHour());


		// 3.2 get MINUTE value from LocalTime
		System.out.print("2. Minutes is : " + time3.getMinute());
	}
}

Output:

LocalTime using 1st variant is = 11:45:37.987

1. Hour is : 11
2. Minutes is : 45
3. Seconds is : 37
4. Nano Seconds is : 987000000

LocalTime using 2nd variant is = 07:18:23

1. Hour is : 7
2. Minutes is : 18
3. Seconds is : 23

LocalTime using 3rd variant is = 05:31

1. Hour is : 5
2. Minutes is : 31

3.3 LocalTime.parse() method – get Time in String-form

LocalTimeExampleUsingParseMethod.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class LocalTimeExampleUsingParseMethod {

	public static void main(String[] args) {

		// 1. specific start-time
		String officeStartTime = "08:29:59.987654321";


		// 1.1 convert/parse to timeInString to LocalTime
		LocalTime startTime = LocalTime.parse(officeStartTime);
		System.out.println("Parsed Start Time is :- \n" + startTime);



		// 2. specific end-time
		String officeEndTime = "05:30:01.123456789";


		// 2.1 convert/parse to timeInString to LocalTime
		LocalTime endTime = LocalTime.parse(officeEndTime);
		System.out.println("\nParsed End Time is :- \n" + endTime);



		// 3. only hour, minute and second
		String time3 = "11:39:47";


		// 3.1 convert/parse to timeInString to LocalTime
		LocalTime localTime3 = LocalTime.parse(time3);
		System.out.println("\nParsed Time is :- \n" + localTime3);



		// 4. only hour and minute
		String time4 = "10:59";


		// 4.1 convert/parse to timeInString to LocalTime
		LocalTime localTime4 = LocalTime.parse(time4);
		System.out.print("\nParsed Time is :- \n" + localTime4);
	}
}

Output:

Parsed Start Time is :- 
08:29:59.987654321

Parsed End Time is :- 
05:30:01.123456789

Parsed Time is :- 
11:39:47

Parsed Time is :- 
10:59

3.4 Adding Nano/Second/Minute/Hour to LocalTime :

  1. Add 125 Nanos to current system LocalTime using plusNanos() method
  2. Add 37 Seconds to current system LocalTime using plusSeconds() method
  3. Add 19 Minutes to current system LocalTime using plusMinutes() method
  4. Add 5 Hours to current system LocalTime using plusHours() method
  5. Read Java 8 – How to add Hour, Minute and Second fields to LocalTime ? for more details and examples

AddToLocalTime.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class AddToLocalTime {

	public static void main(String[] args) {

		// 1. get current system time
		LocalTime localTime = LocalTime.now();
		System.out.println("Current System Time is - " + localTime);


		// 1.1 add 125 NanoSeconds to current system time
		LocalTime add_125_Nanos = localTime.plusNanos(125);
		System.out.println("\n1. After adding 125 Nano Seconds to Current System Time is - " 
				+ add_125_Nanos);


		// 1.2 add 37 Seconds to current system time
		LocalTime add_37_Seconds = localTime.plusSeconds(37);
		System.out.println("2. After adding 37 Seconds to Current System Time is - " 
				+ add_37_Seconds);


		// 1.3 add 19 Minutes to current system time
		LocalTime add_19_Minutes = localTime.plusMinutes(19);
		System.out.println("3. After adding 19 Minutes to Current System Time is - " 
				+ add_19_Minutes);


		// 1.4 add 5 Hours to current system time
		LocalTime add_5_Hours = localTime.plusHours(5);
		System.out.print("4. After adding 5 Hours to Current System Time is - " 
				+ add_5_Hours);
	}
}

Output:

Current System Time is - 17:24:40.307015700

1. After adding 125 Nano Seconds to Current System Time is - 17:24:40.307015825
2. After adding 37 Seconds to Current System Time is - 17:25:17.307015700
3. After adding 19 Minutes to Current System Time is - 17:43:40.307015700
4. After adding 5 Hours to Current System Time is - 22:24:40.307015700

3.5 Subtracting Nano/Second/Minute/Hour from LocalTime :

  1. Subtract 125 Nanos from current system LocalTime using minusNanos() method
  2. Subtract 37 Seconds from current system LocalTime using minusSeconds() method
  3. Subtract 19 Minutes from current system LocalTime using minusMinutes() method
  4. Subtract 5 Hours from current system LocalTime using minusHours() method
  5. Read Java 8 – How to subtract Hour, Minute and Second fields from LocalTime ? for more details and examples

SubtractFromLocalTime.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class SubtractFromLocalTime {

	public static void main(String[] args) {

		// 1. get current system time
		LocalTime localTime = LocalTime.now();
		System.out.println("Current System Time is - " + localTime);


		// 1.1 subtract 125 NanoSeconds from current system time
		LocalTime sub_125_Nanos = localTime.minusNanos(125);
		System.out.println("\n1. After subtracting 125 Nano Seconds from Current System Time is - " 
				+ sub_125_Nanos);


		// 1.2 subtract 37 Seconds from current system time
		LocalTime sub_37_Seconds = localTime.minusSeconds(37);
		System.out.println("2. After subtracting 37 Seconds from Current System Time is - " 
				+ sub_37_Seconds);


		// 1.3 subtract 19 Minutes from current system time
		LocalTime sub_19_Minutes = localTime.minusMinutes(19);
		System.out.println("3. After subtracting 19 Minutes from Current System Time is - " 
				+ sub_19_Minutes);


		// 1.4 subtract 5 Hours from current system time
		LocalTime sub_5_Hours = localTime.minusHours(5);
		System.out.print("4. After subtracting 5 Hours from Current System Time is - " 
				+ sub_5_Hours);
	}
}

Output:

Current System Time is - 17:25:39.554995

1. After subtracting 125 Nano Seconds from Current System Time is - 17:25:39.554994875
2. After subtracting 37 Seconds from Current System Time is - 17:25:02.554995
3. After subtracting 19 Minutes from Current System Time is - 17:06:39.554995
4. After subtracting 5 Hours from Current System Time is - 12:25:39.554995

3.6 Formatting LocalTime using DateTimeFormatter:

FormattingLocalTimeUsingFormatMethod.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class FormattingLocalTimeUsingFormatMethod {

	public static void main(String[] args) {

		// 1. get current system date
		LocalTime localTime = LocalTime.now();
		System.out.println("Current Time in ISO_LOCAL_TIME format is = " + localTime);


		// 1.1 format to HH:mm:ss.nnn
		String formattedDate = localTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.nnn"));
		System.out.println("\n1. LocalTime in HH:mm:ss.nnn format is = " + formattedDate);


		// 1.2 format to HH:mm:ss
		String formattedDate2 = localTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
		System.out.println("2. LocalTime in HH:mm:ss format is = " + formattedDate2);



		// 2. form LocalTime using of() passing hour, minute, second and nano
		LocalTime localTime2 = LocalTime.of(5, 27, 53, 987123654);
		System.out.println("\nLocalTime in ISO_LOCAL_TIME format is = " + localTime2);


		// 1.1 format to HH:mm
		String formattedDate3 = localTime2.format(DateTimeFormatter.ofPattern("HH:mm"));
		System.out.println("\n1. LocalTime in HH:mm format is = " + formattedDate3);


		// 1.2 format to HH:mm:ss:nn
		String formattedDate4 = localTime2.format(DateTimeFormatter.ofPattern("HH:mm:ss:nnnnn"));
		System.out.print("2. LocalTime in HH:mm:ss:nn format is = " + formattedDate4);
	}
}

Output:

Current Time in ISO_LOCAL_TIME format is = 17:27:31.448111500

1. LocalTime in HH:mm:ss.nnn format is = 17:27:31.448111500
2. LocalTime in HH:mm:ss format is = 17:27:31

LocalTime in ISO_LOCAL_TIME format is = 05:27:53.987123654

1. LocalTime in HH:mm format is = 05:27
2. LocalTime in HH:mm:ss:nn format is = 05:27:53:987123654

3.7 Altering Nano/Second/Minute/Hour fields with LocalTime:

  • Altering Hour, Minute, Second and Nano-second field/part of LocalTime is possible with the help below methods,
    • withHour() – This method alters hour part/field of the invoking LocalTime
    • withMinute() – This method alters minute part/field of the invoking LocalTime
    • withSecond() – This method alters second part/field of the invoking LocalTime
    • withNano() -This method alters nano-second part/field of the invoking LocalTime
  • Read Java 8 – How to alter Hour, Minute and Second fields of LocalTime ? for more details and examples

AlterLocalTime.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class AlterLocalTime {

	public static void main(String[] args) {

		// 1. get current system Time
		LocalTime localTime = LocalTime.now();
		System.out.println("Current System Time in ISO_LOCAL_TIME format is = " 
				+ localTime);


		// 1.1 alter hour part to current system Time
		LocalTime hourAltered = localTime.withHour(5);
		System.out.println("\n1. Hours (5) altered in current system Time is = " 
				+ hourAltered);


		// 1.2 alter minute part to current system Date/time
		LocalTime minuteAltered = localTime.withMinute(19); 
		System.out.println("2. Minutes (19) altered in current system Time is = " 
				+ minuteAltered);


		// 1.3 alter second part to current system Date/time
		LocalTime secondAltered = localTime.withSecond(47);
		System.out.println("3. Seconds (47) altered in current system Time is = " 
				+ secondAltered);


		// 1.4 alter nano part to current system Date/time
		LocalTime nanoAltered = localTime.withNano(125);
		System.out.print("4. Nanoseconds (125) altered in current system Time is = "
				+ nanoAltered);
	}
}

Output:

Current System Time in ISO_LOCAL_TIME format is = 17:29:15.718410400

1. Hours (5) altered in current system Time is = 05:29:15.718410400
2. Minutes (19) altered in current system Time is = 17:19:15.718410400
3. Seconds (47) altered in current system Time is = 17:29:47.718410400
4. Nanoseconds (125) altered in current system Time is = 17:29:15.000000125

3.8 Check LocalTime is Before/After another LocalTime :

Compare2LocalTime.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class Compare2LocalTime {

	public static void main(String[] args) {

		// 1. get current system time
		LocalTime currentTime = LocalTime.of(17, 29, 59, 999);
		System.out.println("1. Current System Time = " + currentTime);


		// 2. form past LocalTime
		LocalTime pastTime = LocalTime.MIDNIGHT;
		System.out.println("2. Past Time is = " + pastTime);


		// 3. form future LocalTime
		LocalTime lastTime = LocalTime.MAX;
		System.out.println("3. Future Time is = " + lastTime);


		// 4. isBefore() - LocalTime comparison
		System.out.println("\n\n4. Comparison with isBefore() method :- \n");


		// 4.1 check whether currentTime isBefore lastTime
		boolean isBefore = currentTime.isBefore(lastTime);
		System.out.println("4.1 Current Time (" + currentTime 
				+ ") is Before Future Time (" + lastTime + ") ? "
				+ isBefore);


		// 4.2 check whether currentTime isBefore pastTime
		boolean isBefore2 = currentTime.isBefore(pastTime);
		System.out.println("4.2 Current Time (" + currentTime 
				+ ") is Before Past Time (" + pastTime + ") ? "
				+ isBefore2);


		// 5. isAfter() - LocalTime comparison
		System.out.println("\n\n5. Comparison with isAfter() method :- \n");


		// 5.1 check whether currentTime isAfter pastTime
		boolean isAfter = currentTime.isAfter(pastTime);
		System.out.println("5.1 Current Time (" + currentTime 
				+ ") is After Past Time (" + pastTime + ") ? "
				+ isAfter);


		// 5.2 check whether currentTime isAfter lastTime
		boolean isAfter2 = currentTime.isAfter(lastTime);
		System.out.print("5.2 Current Time (" + currentTime 
				+ ") is After Future Time (" + lastTime + ") ? "	
				+ isAfter2);

	}
}

Output:

1. Current System Time = 17:29:59.000000999
2. Past Time is = 00:00
3. Future Time is = 23:59:59.999999999


4. Comparison with isBefore() method :- 

4.1 Current Time (17:29:59.000000999) is Before Future Time (23:59:59.999999999) ? true
4.2 Current Time (17:29:59.000000999) is Before Past Time (00:00) ? false


5. Comparison with isAfter() method :- 

5.1 Current Time (17:29:59.000000999) is After Past Time (00:00) ? true
5.2 Current Time (17:29:59.000000999) is After Future Time (23:59:59.999999999) ? false

3.9 Convert LocalTime to LocalDateTime/OffsetTime :

ConvertLocalTime.java

package in.bench.resources.localtime.sorting;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;

public class ConvertLocalTime {

	public static void main(String[] args) {

		// get current system time
		LocalTime localTime = LocalTime.now();
		System.out.println("Current System Time is :- \n" + localTime);


		// 1. convert LocalTime to LocalDateTime by current system date using atDate() method
		LocalDateTime localDateTime = localTime.atDate(LocalDate.now());
		System.out.println("\n1. LocalTime to LocalDateTime is :- \n" + localDateTime);


		// 2. convert LocalDate to OffsetTime using atOffset() method - add system default zone info
		OffsetTime offsetTime = localTime.atOffset(ZoneOffset.of("+05:30"));
		System.out.print("\n2. LocalDate to OffsetTime is :- \n" + offsetTime);
	}
}

Output:

Current System Time is :- 
11:48:24.980632400

1. LocalTime to LocalDateTime is :- 
2022-08-06T11:48:24.980632400

2. LocalDate to OffsetTime is :- 
11:48:24.980632400+05:30

3.10 Convert LocalTime to number of Seconds and vice-versa :

  • toSecondOfDay() – This method converts LocalTime into Seconds or seconds of day ranging from 0 seconds to 86399 seconds
  • ofSecondOfDay(long) – This method converts given seconds in long format to LocalTime in the default (HH:mm:ss) format

ConvertLocalTimeToSecondsAndViceVersa.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class ConvertLocalTimeToSecondsAndViceVersa {

	public static void main(String[] args) {

		// 1. Conversion of LocalTime to number of Seconds
		System.out.println("1. Conversion of LocalTime to number of Seconds :-");

		// 1.1 get system time
		LocalTime localTime1 = LocalTime.now();
		System.out.println("\nCurrent System Time is :- \n" + localTime1);


		// 1.2 convert LocalTime to Seconds using toSecondOfDay() between (0 - 86399) seconds
		int seconds1 = localTime1.toSecondOfDay();
		System.out.println("\nConversion of LocalTime to Seconds in int format "
				+ "using toSecondOfDay() is :- \n"
				+ seconds1);


		// 2. Conversion of Seconds in long format to LocalTime
		System.out.println("\n\n2. Conversion of Seconds in long format to LocalTime :-");


		// 2.1 seconds in long format
		long seconds2 = 76528L;
		//long seconds = 86499L;
		System.out.println("\nNumber of seconds in long format is :- \n"
				+ seconds2);


		// 2.2 convert Second of Day to LocalTime using LocalTime.ofSecondOfDay()
		LocalTime localTime2 = LocalTime.ofSecondOfDay(seconds2);
		System.out.print("\nSeconds to LocalTime"
				+ " using LocalTime.ofSecondOfDay() is :- \n"
				+ localTime2);
	}
}

Output:

1. Conversion of LocalTime to number of Seconds :-

Current System Time is :- 
14:17:09.706628400

Conversion of LocalTime to Seconds in int format using toSecondOfDay() is :- 
51429


2. Conversion of Seconds in long format to LocalTime :-

Number of seconds in long format is :- 
76528

Seconds to LocalTime using LocalTime.ofSecondOfDay() is :- 
21:15:28

3.11 Convert LocalTime to number of Nanoeconds and vice-versa :

  • toNanoOfDay() – This method converts LocalTime into Nanoseconds or nano of day ranging from 0 nanoseconds to 86399999999999 nanoseconds
  • ofNanoOfDay() – This method converts given nanoseconds in long format to LocalTime in the default (HH:mm:ss.nnn) format

ConvertLocalTimeToNanosecondsAndViceVersa.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;

public class ConvertLocalTimeToNanosecondsAndViceVersa {

	public static void main(String[] args) {

		// 1. Conversion of LocalTime to number of Nanoseconds
		System.out.println("1. Conversion of LocalTime to number of Nanoseconds :-");


		// 1.1 get system time
		LocalTime localTime1 = LocalTime.now();
		System.out.println("\nCurrent System Time is :- \n" + localTime1);


		// 1.2 convert LocalTime to nanoseconds using toNanoOfDay() 
		long nanoseconds1 = localTime1.toNanoOfDay();
		System.out.println("\nConversion of LocalTime to Nanoseconds in long format "
				+ "using toNanoOfDay() is :- \n"
				+ nanoseconds1);


		// 2. Conversion of Seconds in long format to LocalTime
		System.out.println("\n\n2. Conversion of Nanoseconds in long format to LocalTime :-");


		// 2.1 seconds in long format
		long nanoseconds2 = 75125899139899L;
		System.out.println("\nNumber of nanoseconds in long format is :- \n"
				+ nanoseconds2);


		// 2.2 convert Nanosecond of Day to LocalTime using LocalTime.ofNanoOfDay()
		LocalTime localTime2 = LocalTime.ofNanoOfDay(nanoseconds2);
		System.out.print("\nNanoseconds to LocalTime"
				+ " using LocalTime.ofNanoOfDay() is :- \n"
				+ localTime2);
	}
}

Output:

1. Conversion of LocalTime to number of Nanoseconds :-

Current System Time is :- 
14:17:30.805328900

Conversion of LocalTime to Nanoseconds in long format using toNanoOfDay() is :- 
51450805328900


2. Conversion of Nanoseconds in long format to LocalTime :-

Number of nanoseconds in long format is :- 
75125899139899

Nanoseconds to LocalTime using LocalTime.ofNanoOfDay() is :- 
20:52:05.899139899

3.12 Check Temporal Fields supported by LocalTime :

CheckLocalTimeIsSupportedUsingTemporalField.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class CheckLocalTimeIsSupportedUsingTemporalField {

	public static void main(String[] args) {

		// get current system time
		LocalTime localTime = LocalTime.now();
		System.out.println("Current LocalTime is = \n" + localTime);


		// 1. check ChronoField.NANO_OF_SECOND field supported ?
		System.out.println("\n1. LocalTime.isSupported(ChronoField.NANO_OF_SECOND) ? " + 
				localTime.isSupported(ChronoField.NANO_OF_SECOND));


		// 2. check ChronoField.SECOND_OF_MINUTE field supported ?
		System.out.println("\n2. LocalTime.isSupported(ChronoField.SECOND_OF_MINUTE) ? " + 
				localTime.isSupported(ChronoField.SECOND_OF_MINUTE));


		// 3. check ChronoField.HOUR_OF_DAY field supported ?
		System.out.println("\n3. LocalTime.isSupported(ChronoField.HOUR_OF_DAY) ? " + 
				localTime.isSupported(ChronoField.HOUR_OF_DAY));


		// 4. check ChronoField.YEAR field supported ?
		System.out.print("\n4. LocalTime.isSupported(ChronoField.YEAR) ? " + 
				localTime.isSupported(ChronoField.YEAR));
	}
}

Output:

Current LocalTime is = 
16:44:00.557388800

1. LocalTime.isSupported(ChronoField.NANO_OF_SECOND) ? true

2. LocalTime.isSupported(ChronoField.SECOND_OF_MINUTE) ? true

3. LocalTime.isSupported(ChronoField.HOUR_OF_DAY) ? true

4. LocalTime.isSupported(ChronoField.YEAR) ? false

3.13 Check Temporal Units supported by LocalTime :

CheckLocalTimeIsSupportedUsingTemporalUnit.java

package in.bench.resources.localtime.sorting;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class CheckLocalTimeIsSupportedUsingTemporalUnit {

	public static void main(String[] args) {

		// get current system time
		LocalTime localTime = LocalTime.now();
		System.out.println("Current LocalTime is = \n" + localTime);


		// 1. check ChronoUnit.NANOS field supported ?
		System.out.println("\n1. LocalTime.isSupported(ChronoUnit.NANOS) ? " + 
				localTime.isSupported(ChronoUnit.NANOS));


		// 2. check ChronoUnit.SECONDS field supported ?
		System.out.println("\n2. LocalTime.isSupported(ChronoUnit.SECONDS) ? " + 
				localTime.isSupported(ChronoUnit.SECONDS));


		// 3. check ChronoUnit.HOURS field supported ?
		System.out.println("\n3. LocalTime.isSupported(ChronoUnit.HOURS) ? " + 
				localTime.isSupported(ChronoUnit.HOURS));


		// 4. check ChronoUnit.DAYS field supported ?
		System.out.print("\n4. LocalTime.isSupported(ChronoUnit.DAYS) ? " + 
				localTime.isSupported(ChronoUnit.DAYS));
	}
}

Output:

Current LocalTime is = 
16:44:18.943597800

1. LocalTime.isSupported(ChronoUnit.NANOS) ? true

2. LocalTime.isSupported(ChronoUnit.SECONDS) ? true

3. LocalTime.isSupported(ChronoUnit.HOURS) ? true

4. LocalTime.isSupported(ChronoUnit.DAYS) ? false

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – LocalDateTime with method details and examples
Java 8 - LocalDate with method details and examples