Java 8 – How to convert LocalTime to an OffsetDateTime ?

In this article, we will learn how to convert LocalTime to an OffsetDateTime by adding/combining date & Offset informations using atDate() & atOffset() methods provided in Java 1.8 version

For OffsetDateTime to LocalTime conversion, read Java 8 – How to extract LocalDate and LocalTime and LocalDateTime from OffsetDateTime ?

Convert LocalTime to an OffsetDateTime :

Direct conversion between LocalTime and OffsetDateTime isn’t possible hence convert LocalTime to LocalDateTime using atDate() method and then convert LocalDateTime to an OffsetDateTime using atOffset() method

  • First, convert LocalTime to LocalDateTime using atDate() method –
    • atDate(LocalDate) – This method combines invoking LocalTime with a provided LocalDate to create a LocalDateTime
  • Second, convert LocalDateTime to an OffsetDateTime using atOffset() method –
    • atOffset(ZoneOffset) – This method combines invoking date-time with an offset to create an OffsetDateTime

ConvertLocalTimeToOffsetDateTime.java

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

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

public class ConvertLocalTimeToOffsetDateTime {

	public static void main(String[] args) {

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


		// 2. get current system date
		LocalDate localDate = LocalDate.now();
		System.out.println("\nCurrent System Date is :- \n" 
				+ localDate);


		// 3. First, convert LocalTime to LocalDateTime using atDate() - add current system date
		LocalDateTime localDateTime = localTime.atDate(localDate);
		System.out.println("\nLocalDateTime is :- \n" 
				+ localDateTime);


		// 4. default ZoneOffset
		ZoneOffset zoneOffset = ZoneOffset.of("+05:30");
		System.out.println("\nDefault ZoneOffset is :- \n" 
				+ zoneOffset);


		// 5. First, convert LocalTime -> LocalDateTime -> OffsetDateTime
		OffsetDateTime offsetDateTime = localDateTime.atOffset(zoneOffset);
		System.out.print("\nConversion of LocalTime to OffsetDateTime using atOffset() is :- \n" 
				+ offsetDateTime);
	}
}

Output:

Current System Time is :- 
19:54:47.905765400

Current System Date is :- 
2022-08-23

LocalDateTime is :- 
2022-08-23T19:54:47.905765400

Default ZoneOffset is :- 
+05:30

Conversion of LocalTime to OffsetDateTime using atOffset() is :- 
2022-08-23T19:54:47.905765400+05:30

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert LocalTime to an Instant ?
Java 8 – How to convert LocalTime to ZonedDateTime ?