Java Convert LocalTime to OffsetTime

Tags: Java LocalTime Java OffsetTime Java 8

In this Java core tutorial we learn how to convert a java.time.LocalTime object to an java.time.OffsetTime object in Java programming language.

How to convert LocalTime to OffsetTime in Java

To convert a LocalTime object to OffsetTime object we can combine the LocalTime with a time offset represent by ZoneOffset class. For example, in the following Java program we combine a LocalTime with a time offset from system time zone to create a new OffsetTime object.

ConvertLocalTimeToOffsetTimeExample1.java

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

public class ConvertLocalTimeToOffsetTimeExample1 {
    public static void main(String... args) {
        LocalTime localTime = LocalTime.of(20, 30, 50);
        ZoneOffset zoneOffset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
        OffsetTime offsetTime = localTime.atOffset(zoneOffset);

        System.out.println("LocalTime: " + localTime);
        System.out.println("ZoneOffset: " + zoneOffset);
        System.out.println("OffsetTime: " + offsetTime);
    }
}
The output as below.
LocalTime: 20:30:50
ZoneOffset: +07:00
OffsetTime: 20:30:50+07:00

In the following Java program we show how to combine LocalTime with UTC time offset to create OffsetTime in UTC time zone.

ConvertLocalTimeToOffsetTimeExample2.java

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

public class ConvertLocalTimeToOffsetTimeExample2 {
    public static void main(String... args) {
        LocalTime localTime = LocalTime.of(20, 30, 50);
        ZoneOffset zoneOffset = ZoneOffset.UTC;
        OffsetTime offsetTime = localTime.atOffset(zoneOffset);

        System.out.println("LocalTime: " + localTime);
        System.out.println("ZoneOffset: " + zoneOffset);
        System.out.println("OffsetTime: " + offsetTime);
    }
}
The output as below.
LocalTime: 20:30:50
ZoneOffset: Z
OffsetTime: 20:30:50Z

Happy Coding 😊

Java Convert LocalTime to String

Java Convert LocalTime to Seconds of Day

Java Convert LocalTime to Nanos of Day

Java Convert LocalTime to Epoch Seconds

Java Convert LocalTime to LocalDateTime

Java Convert LocalTime to Date

Java Convert LocalTime to Calendar

Java LocalTime by Examples

Java LocalDate by Examples

Java LocalDateTime by Examples

Java Date by Examples

Java Calendar by Examples

Java Calendar using Calendar.Builder by Examples