Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, December 1, 2020

Java 8 - Convert Date Time From One Timezone To Another

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.


No comments:

Post a Comment

Please do not add any spam links in the comments section.