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

In this article, we will learn how to add Hour or Minute or Second or Nanosecond fields to LocalTime using different methods provided in Java 1.8 version

Adding Nano/Second/Minute/Hour to LocalTime :

  • It is very simple to add Nanosecond or Second or Minute or Hour fields to LocalTime using below methods,
    1. plusNanos() – Returns a copy of invoking LocalTime with the specified number of nanoseconds added
    2. plusSeconds() – Returns a copy of invoking LocalTime with the specified number of seconds added
    3. plusMinutes() – Returns a copy of invoking LocalTime with the specified number of minutes added
    4. plusHours() – Returns a copy of invoking LocalTime with the specified number of hours added
  • In the below illustration, we are going to do below operations with current 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
  • Finally, print LocalTime to the console for above operations

AddToLocalTime.java

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

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 - 09:43:31.623506

1. After adding 125 Nano Seconds to Current System Time is - 09:43:31.623506125
2. After adding 37 Seconds to Current System Time is - 09:44:08.623506
3. After adding 19 Minutes to Current System Time is - 10:02:31.623506
4. After adding 5 Hours to Current System Time is - 14:43:31.623506

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to subtract Hour, Minute and Second fields from LocalTime ?
Java 8 – How to convert LocalTime to Nanoseconds and vice-versa ?