Java 8 – How to convert LocalTime to ZonedDateTime ?

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

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

Convert LocalTime to ZonedDateTime :

Direct conversion between LocalTime and ZonedDateTime isn’t possible hence convert LocalTime to LocalDateTime using atDate() method and then convert LocalDateTime to ZonedDateTime using atZone() 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 ZonedDateTime using atZone() method –
    • atZone(ZoneId) – This method combines invoking date-time with a time-zone to create a ZonedDateTime

ConvertLocalTimeToZonedDateTime.java

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

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ConvertLocalTimeToZonedDateTime {

	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 zone
		ZoneId zoneId = ZoneId.systemDefault();
		System.out.println("\nDefault Zone is :- \n" 
				+ zoneId);


		// 5. First, convert LocalTime -> LocalDateTime -> ZonedDateTime
		ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
		System.out.print("\nConversion of LocalTime to ZonedDateTime using atZone() is :- \n" 
				+ zonedDateTime);
	}
}

Output:

Current System Time is :- 
19:48:39.599350900

Current System Date is :- 
2022-08-23

LocalDateTime is :- 
2022-08-23T19:48:39.599350900

Default Zone is :- 
Asia/Calcutta

Conversion of LocalTime to ZonedDateTime using atZone() is :- 
2022-08-23T19:48:39.599350900+05:30[Asia/Calcutta]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert LocalTime to an OffsetDateTime ?
Java 9 – How to convert Instant to LocalDate using ofInstant() method ?