Java 8 – How to convert LocalTime to an OffsetTime ?

In this article, we will learn how to convert LocalTime to OffsetTime by adding/combining ZoneOffset information using atOffset() method of LocalTime provided in Java 1.8 version

Convert LocalTime to an OffsetTime :

  • atOffset(ZoneOffset) – This method combines invoking LocalTime with a provided ZoneOffset to create an OffsetTime
  • Adding zone offset information to LocalTime will return OffsetTime

ConvertLocalTimeToOffsetTime.java

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

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

public class ConvertLocalTimeToOffsetTime {

	public static void main(String[] args) {

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


		// 2. ZoneOffset to be added to current LocalTime
		ZoneOffset zoneOffset = ZoneOffset.of("+05:30");
		System.out.println("\nZoneOffset to be added to current LocalTime :- \n" + zoneOffset);


		// 2. convert LocalTime to OffsetTime using atOffset() - add system default zone info
		OffsetTime offsetTime = localTime.atOffset(zoneOffset);
		System.out.print("\nConversion of LocalTime to OffsetTime "
				+ "using atOffset() is :- \n"
				+ offsetTime);
	}
}

Output:

Current System Time is :- 
09:27:46.256212500

ZoneOffset to be added to current LocalTime :- 
+05:30

Conversion of LocalTime to OffsetTime using atOffset() is :- 
09:27:46.256212500+05:30

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert LocalTime to Seconds and vice-versa ?
Java 8 – How to convert LocalTime to LocalDateTime ?