1. Overview
In this article, we will Learn to Convert date and time to different timezone or any given date-time object from one timezone to another timezone using java. We will also show you some examples using ZonedDateTime.
Let’s take one example, suppose we create one meeting invite for 12th November at 12 pm and we need to send this invite to all over the country for the different users now for each country at (12th November at 12 pm) is a different time. So now we need to convert the date and time to each country based on the meeting invite time.
2. Code setup
package practice.String; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class TimezoneExample { private static final String DATE_FORMAT ="dd-M-yyyy hh:mm:ss a"; private static final String TIME_FORMAT ="hh:mm a"; public static void main(String[] args) { String dateInstring ="12-11-2022 12:00:00 PM"; String defaultTimezone="GMT"; String setTimezone="Africa/Johannesburg"; LocalDateTime ldt = LocalDateTime.parse(dateInstring, DateTimeFormatter.ofPattern(DATE_FORMAT)); ZoneId gmtZoneId=ZoneId.of(defaultTimezone); System.out.println("default time zone:"+gmtZoneId); ZonedDateTime asiaZonedDateTime = ldt.atZone(gmtZoneId); System.out.println("default Date time zone:"+asiaZonedDateTime); ZoneId newYokZoneId=ZoneId.of(setTimezone); System.out.println("user input time zone:"+asiaZonedDateTime); ZonedDateTime newDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId); System.out.println("display output Date time zone:"+newDateTime); DateTimeFormatter formate =DateTimeFormatter.ofPattern(TIME_FORMAT); String localTimeString = formate.format(newDateTime); System.out.println("display time:"+localTimeString); } }
Output:
default time zone:GMT
default Date time zone:2022-11-12T12:00Z[GMT]
user input time zone:2022-11-12T12:00Z[GMT]
display output Date time zone:2022-11-12T14:00+02:00[Africa/Johannesburg]
display time:02:00 PM
Read more topics related to java
- Multithreading in java
- Inter thread communication in java
- synchronization in java
- Exception in java
- Inner class in java
Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.