Java 8 – How to form LocalTime passing Hour, Minute and Second fields ?

In this article, we will learn how to form LocalTime passing hours, minutes, seconds and nanoseconds fields using variants of LocalTime.of() method provided in the Java 1.8 version

Form LocalTime passing Hours, Minutes, Seconds and Nanoseconds :

  • LocalTime.of() method returns LocalTime passing hours, minutes, seconds and nanoseconds fields
  • There are 3 variants of LocalTime.of() methods –
    • of(hour, minute, second, nanoOfSecond) – get an instance of LocalTime from an hour, minute, second and nanosecond
    • of(hour, minute, second) – get an instance of LocalTime from an hour, minute and second
    • of(hour, minute) – get an instance of LocalTime from an hour and minute
  • Finally, print LocalTime and different formatted style of LocalTime to the console

FormLocalTime.java

package in.bench.resources.java8.localtime.examples;

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

public class FormLocalTime {

	public static void main(String[] args) {

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


		// 1.1 format localTime1
		String formattedStr1 = localTime1.format(
				DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
		System.out.println("Formatted LocalTime 1 is = " + formattedStr1); 



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


		// 2.1 format localTime2
		String formattedStr2 = localTime2.format(
				DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
		System.out.println("Formatted LocalTime 2 is = " + formattedStr2);



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


		// 3.1 format localTime3
		String formattedStr3 = localTime3.format(
				DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
		System.out.print("Formatted LocalTime 3 is = " + formattedStr3);
	}
}

Output:

LocalTime using 1st variant is = 13:45:37.987
Formatted LocalTime 1 is = 1:45:37 pm

LocalTime using 2nd variant is = 19:18:23
Formatted LocalTime 2 is = 7:18:23 pm

LocalTime using 3rd variant is = 05:31
Formatted LocalTime 3 is = 5:31 am

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to parse LocalTime in String form ?
Java 8 - How to get Hour, Minute and Second fields from LocalTime ?