Convert from ZonedDateTime to LocalDateTime with a timezone

Below is the Java example to convert ZonedDateTime to LocalDateTime with a timezone.

ZonedDateTime to LocalDateTime Example

ZonedDateTime represents immutable date-time with a timezone. And now() obtains the current system date-time in the default timezone if timezone ID is not specified using  ZoneId.

ZoneId is a timezone ID such as “Asia/Calcutta”.

package com.sneppets.solution;

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

public class ZonedDateTimeToLocalDateTimeExample {
	
	public static void main (String[] args) {
		
		//ZonedDateTime to LocalDateTime with timezone
		ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Calcutta"));
		System.out.println("ZonedDateTime.now():" + zdt);
		LocalDateTime ldt = zdt.toLocalDateTime();
		System.out.println("LocalDateTime:" + ldt);
	}

}

Output

ZonedDateTime.now():2019-12-01T12:38:02.973+05:30[Asia/Calcutta]
LocalDateTime:2019-12-01T12:38:02.973

LocalDateTime to ZonedDateTime

Below example shows you how to convert from local datetime to zoned datetime with ZoneId using atZone() method of LocalDateTime.

For instance, you can use withZoneSameInstant() method with different timezone id to change the offset while keeping the same instant or datetime.

package com.sneppets.solution;

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

public class LocalDateTimeToZonedDateTimeExample {
	
	public static void main (String[] args) {
		
		LocalDateTime ldt = LocalDateTime.now();
		
		System.out.println("LocalDateTime : " + ldt);
		
		ZoneId zone = ZoneId.of("Asia/Calcutta");	
		
		//ZonedDateTime with Asis/Calcutta timezone
		ZonedDateTime zdtAtAsiaCalcutta = ldt.atZone(zone);
		
		System.out.println("ZonedDateTime at Asia/Calcutta : " + zdtAtAsiaCalcutta);
		
		//Same data-time with Europe/Lisbon timezone
		ZonedDateTime zdtAtEuropeLisbon  = zdtAtAsiaCalcutta.withZoneSameInstant(ZoneId.of("Europe/Lisbon"));
		
		System.out.println("ZonedDateTime at Europe/Lisbon : " + zdtAtEuropeLisbon);
	}

}

Output

LocalDateTime : 2019-12-01T13:04:16.864
ZonedDateTime at Asia/Calcutta : 2019-12-01T13:04:16.864+05:30[Asia/Calcutta]
ZonedDateTime at Europe/Lisbon : 2019-12-01T07:34:16.864Z[Europe/Lisbon]

Further Learning

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments