Java 8 – How to convert LocalDateTime to ZonedDateTime ?

In this article, we will learn how to convert LocalDateTime to ZonedDateTime using atZone(ZoneId) method of LocalDateTime provided in Java 1.8 version

For ZonedDateTime to LocalDateTime conversion, read Java 8 – How to convert ZonedDateTime to LocalDateTime ?

Convert LocalDateTime to ZonedDateTime :

  • LocalDateTime has a method atZone() which takes ZoneId as argument and returns ZonedDateTime
    • atZone() – Returns a zoned date-time from invoking LocalDateTime with a time-zone
  • Using this method, it is very easy to convert LocalDateTime to ZonedDateTime by adding time-zone information
  • After conversion, ZonedDateTime have Date & Time parts are same as that of LocalDateTime
  • Lets see an example for conversion of LocalDateTime to ZonedDateTime in the below illustration

ConvertLocalDateTimeToZonedDateTime.java

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

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

public class ConvertLocalDateTimeToZonedDateTime {

	public static void main(String[] args) {

		// 1. get current System Date/time
		LocalDateTime localDateTime = LocalDateTime.now();
		System.out.println("Current System Date/time is :- \n" + localDateTime);


		// 2. get system default zone
		ZoneId zoneId = ZoneId.systemDefault();
		System.out.println("\nDefault System Zone is :- \n" + zoneId);


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

Output:

Current System Date/time is :- 
2022-08-09T12:35:41.106583900

Default System Zone is :- 
Asia/Calcutta

Conversion of LocalDateTime to ZonedDateTime is :- 
2022-08-09T12:35:41.106583900+05:30[Asia/Calcutta]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert LocalDateTime to an OffsetDateTime ?
Java 8 – How to convert LocalDateTime in different Format Style ?