$show=/label

Java 8 - Convert Date Time From One Timezone To Another

SHARE:

A quick guide to convert date and time from one timezone to another timezone with example programs using ZonedDateTime in java 8 and older Java Date.

1. Overview

In this tutorial, We'll learn how to work with date and time timezone conversions using new java 8 date time api and older java versions classes Date, Calendar API's.

Some of the times you need to send the emails or notifications to user based on his profile timezone settings.

In that case you need to convert the date time from current system timezone to another timezone. 

There is another case where flight timings will be difficult to calculate based on the arriving city. Flight starts from San Francisco (SFO) at 11:00 AM and arrives in Dubai(DXB) at 23:20. This journey takes up to 24 hours 20 minutes but when we see it looks like 12 hours 20 minutes. This is because of timezone differences.

First, let us try to convert the current time into multiple timezones using java 8 ZonedDateTime api. Next, using older java api such as java.util.Date and java.util.Calendar classes.

Finally, We'll explore how to solve flight problem using java 8 ZonedDateTime api.

Java 8 - Convert Date Time From One Timezone To Another


2. Java 8 and Beyond TimeZone Conversion


Example to convert the current date and time to one timezone to another timezone.

Steps:

Step 1: Create current date and time using ZonedDateTime.now() method.
Step 2: Create a timezone for Los Angeles using ZoneId.of() method.
Step 3: Create a timezone for Dubai country using ZoneId.of() method.
Step 4: Convert IST time to Los Angeles timezone using ZonedDateTime.withZoneSameInstant() and pass the current time to it. The returned object is in Losangeles time zone.
Step 5: Convert IST time to Dubai timezone using ZonedDateTime.withZoneSameInstant() and pass the current time to it. The returned object is in Dubai time zone.
Step 6: Format all 3 dates to "yyyy-MMM-dd HH:mm" using DateTimeFormatter.format() method as string value.

At last, we are getting the time differences between two timezones date times and it should be 0.
package com.javaprogramto.java8.dates.timezone.conversion;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Java8TimeZoneConversion {

	public static void main(String[] args) {

		// Current date and time using now()
		ZonedDateTime currentDateTime = ZonedDateTime.now();

		// Creating two timezone zoneid objects using ZoneId.of() method.
		ZoneId losAngelesTimeZone = ZoneId.of("America/Los_Angeles");
		ZoneId dubaiTimeZone = ZoneId.of("Asia/Dubai");

		// Converting Current timezone time to Log Angeles time
		ZonedDateTime losAngelesDateTime = currentDateTime.withZoneSameInstant(losAngelesTimeZone);

		// Converting Current timezone time to Dubai time
		ZonedDateTime dubaiDateTime = currentDateTime.withZoneSameInstant(dubaiTimeZone);

		// Datetime formatting 
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm z");
		
		// Print all 3 dates
		System.out.println("Current time in IST : " + formatter.format(currentDateTime));
		System.out.println("Los Angeles time now : " + formatter.format(losAngelesDateTime));
		System.out.println("Dubai time now : " + formatter.format(dubaiDateTime));

		// getting the diff b/w two los angeles and dubai times.
		printDurationBetweenTwoDates(losAngelesDateTime, dubaiDateTime);

	}

	private static void printDurationBetweenTwoDates(ZonedDateTime sfoDateTime, ZonedDateTime dubaiDateTime) {
		Duration d = Duration.between(sfoDateTime, dubaiDateTime);
		long days = d.get(ChronoUnit.SECONDS);
		System.out.println("Time Difference between los angeles and dubai : " + days / (60 * 60) + " Hours " + (days % (60 * 60)) / 60 + " Minites");

	}

}
 
Output:
Current time in IST : 2020-Dec-01 16:56 IST
Los Angeles time now : 2020-Dec-01 03:26 PST
Dubai time now : 2020-Dec-01 15:26 GST
Time Difference between los angeles and dubai : 0 Hours 0 Minites
 

3. Older Java Using Date API


If you working on older jdk 1.8 below versions and you have option is java.util.Date api to work with dates.

By default, Date class does not work with the timezones conversions and it always gets the timezone from system.

so, once the date is created then we can not convert into another timezone. So, we need to use the SimpleDateFormat.setTimeZone() method to convert the date time to the given timezone.

In the below example, First created current timezone in IST and the same time converted into PST and GST timezones.

package com.javaprogramto.java8.dates.timezone.conversion;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class BeforeJava8DateTimeZoneConversion {

	public static void main(String[] args) {

		// Getting the current date from java.util.Date class
		Date currentTime = new Date();

		// Date time to current timezone
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm z");
		String ISTTime = dateFormatter.format(currentTime);
		System.out.println("IST time : " + ISTTime);

		// Date time to PST
		// Creating PST timezone
		TimeZone pstTimezone = TimeZone.getTimeZone("America/Los_Angeles");

		// setting pst timezone to formatter.
		dateFormatter.setTimeZone(pstTimezone);

		// converting IST to PST
		String PSTTime = dateFormatter.format(currentTime);
		System.out.println("PST time : " + PSTTime);

		// Date time to GST - Dubai Gulf
		// Creating GST timezone
		TimeZone gstTimezone = TimeZone.getTimeZone("Asia/Dubai");

		// setting pst timezone to formatter.
		dateFormatter.setTimeZone(gstTimezone);

		// converting IST to PST
		String GSTTime = dateFormatter.format(currentTime);
		System.out.println("GST time : " + GSTTime);
	}
}
 
Output:
IST time : 2020-12-01 17:18 IST
PST time : 2020-12-01 03:48 PST
GST time : 2020-12-01 15:48 GST
 

4. Older Java Using Calendar API


Next, Implement the same using java.util.Calendar class and convert into different timezones using calender.setTimezone().
package com.javaprogramto.java8.dates.timezone.conversion;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class BeforeJava8CalendarZoneConversion {

	public static void main(String[] args) {

		// Creating IST timezone
		TimeZone ist = TimeZone.getTimeZone("Asia/Kolkata");

		// Getting the current date from java.util.Calendar class with IST
		Calendar now = Calendar.getInstance(ist);

		// Date time to current timezone
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm z");
		
		// passing the date from calendar object to formatter.
		String ISTTime = dateFormatter.format(now.getTime());
		System.out.println("IST time : " + ISTTime);

		// Date time to PST
		// Creating PST timezone
		TimeZone pstTimezone = TimeZone.getTimeZone("America/Los_Angeles");
		
		// setting PST timezone to calendar
		now.setTimeZone(pstTimezone);

		// converting IST to PST
		String PSTTime = dateFormatter.format(now.getTime());
		System.out.println("PST time : " + PSTTime);

		// Date time to GST - Dubai Gulf
		// Creating GST timezone
		TimeZone gstTimezone = TimeZone.getTimeZone("Asia/Dubai");
		
		// setting GST timezone to calendar
		now.setTimeZone(gstTimezone);

		// converting IST to PST
		String GSTTime = dateFormatter.format(now.getTime());
		System.out.println("GST time : " + GSTTime);
	}
}
 
Output:
IST time : 2020-12-01 17:32 IST
PST time : 2020-12-01 17:32 IST
GST time : 2020-12-01 17:32 IST
 

5. Java 8 and Beyond Flight Timing TimeZone Conversion


Finally, how to create flight time calculation based on the time duration.

Flight starts at San Francisco (SFO): 11:00 AM 
Arrives in Dubai(DXB) : 23:20 PM. 

This journey takes up to 24 hours 20 minutes but if you see the time difference it is just 12 hours 20 minutes and it was wrong because of timezone effect.

Look at the below example code that shows the exact arrival time after adding 24 hours and 20 mins.
After that destination time will be the exact one shown above.

And also we are going to see the time difference between start and destination date times in days with considering the timezones using Duration class.
package com.javaprogramto.java8.dates.timezone.conversion;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Java8FilghtTimingsTimeZoneConversion {

	public static void main(String[] args) {

		// Current date and time using now()
		LocalDateTime currentDateTime = LocalDateTime.of(2020, 12, 01, 11, 00);

		// Creating two timezone zoneid objects using ZoneId.of() method.
		ZoneId losAngelesTimeZone = ZoneId.of("America/Los_Angeles");
		ZoneId dubaiTimeZone = ZoneId.of("Asia/Dubai");

		// Converting Current timezone time to Log Angeles time
		ZonedDateTime losAngelesDateTime = currentDateTime.atZone(losAngelesTimeZone);

		// Converting Current timezone time to Dubai time
		ZonedDateTime dubaiDateTime = losAngelesDateTime.withZoneSameInstant(dubaiTimeZone).plusHours(24).plusMinutes(20);

		// Datetime formatting 
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm");
		
		// Print all 3 dates
		System.out.println("Current time in IST : " + formatter.format(currentDateTime));
		System.out.println("Los Angeles time now : " + formatter.format(losAngelesDateTime));
		System.out.println("Dubai time now : " + formatter.format(dubaiDateTime));

		// getting the diff b/w two los angeles and dubai times.
		printDurationBetweenTwoDates(losAngelesDateTime, dubaiDateTime);

	}

	private static void printDurationBetweenTwoDates(ZonedDateTime sfoDateTime, ZonedDateTime dubaiDateTime) {
		Duration d = Duration.between(sfoDateTime, dubaiDateTime);
		long days = d.get(ChronoUnit.SECONDS);
		System.out.println("Time Difference between los angeles and dubai : " + days / (60 * 60) + " Hours " + (days % (60 * 60)) / 60 + " Minites");

	}

}
 
Output:
Current time in IST : 2020-Dec-01 11:00
Los Angeles time now : 2020-Dec-01 11:00
Dubai time now : 2020-Dec-02 23:20
Time Difference between los angeles and dubai : 24 Hours 20 Minites
 

6. Conclusion


In this article, we've seen how to convert the date between timezones and convert from one timezone to another.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,28,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,93,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,13,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,105,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,104,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,27,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 - Convert Date Time From One Timezone To Another
Java 8 - Convert Date Time From One Timezone To Another
A quick guide to convert date and time from one timezone to another timezone with example programs using ZonedDateTime in java 8 and older Java Date.
https://1.bp.blogspot.com/-kviqy5UvQJ4/X8Y7ZnFHqNI/AAAAAAAADGU/MqJY0lBx0G8xM0rFQZa-17RIxAmvNZ90ACLcBGAsYHQ/w640-h476/Java%2B8%2B-%2BConvert%2BDate%2BTime%2BFrom%2BOne%2BTimezone%2BTo%2BAnother.png
https://1.bp.blogspot.com/-kviqy5UvQJ4/X8Y7ZnFHqNI/AAAAAAAADGU/MqJY0lBx0G8xM0rFQZa-17RIxAmvNZ90ACLcBGAsYHQ/s72-w640-c-h476/Java%2B8%2B-%2BConvert%2BDate%2BTime%2BFrom%2BOne%2BTimezone%2BTo%2BAnother.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/12/java-convert-date-between-timezones.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/12/java-convert-date-between-timezones.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content