Java 8 – Convert between LocalDateTime and ZonedDateTime

Java 8 example to convert LocalDateTime to ZonedDateTime. Also, learn to convert ZonedDateTime to LocalDateTime instance with example.

1. LocalDateTime -> ZonedDateTime

ZonedDateTime = LocalDateTime + ZoneId

LocalDateTime ldt = LocalDateTime.now();			//Local date time

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ); 		//Zone information

ZonedDateTime zdtAtAsia = ldt.atZone( zoneId );		//Local time in Asia timezone

ZonedDateTime zdtAtET = zdtAtAsia
		.withZoneSameInstant( ZoneId.of( "America/New_York" ) ); //Sama time in ET timezone

Output:

2018-07-15T11:27:46.203763100+05:30[Asia/Kolkata]
2018-07-15T01:57:46.203763100-04:00[America/New_York]

2) ZonedDateTime -> LocalDateTime

Use ZonedDateTime.toLocalDateTime() method to get local datetime without timezone information.

ZonedDateTime zdtAtET = ZonedDateTime.now(ZoneId.of("America/New_York"));
		
LocalDateTime ldt = zdtAtET.toLocalDateTime();

System.out.println(zdtAtET);
System.out.println(ldt);

Output:

2018-07-15T01:59:52.054839900-04:00[America/New_York]
2018-07-15T01:59:52.054839900

Happy Learning !!

References:

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.