Tuesday, December 1, 2020

SimpleDateFormat - kk VS HH VS hh in Date Formatting Java

1. Overview

In this tutorial, We'll learn understand the main difference between the kk, HH and hh in date formatting in java.

You might have used these in the date formatting in java working with SimpleDateFormat.

First, understand the diff kk VS HH VS hh in java. Next, we'll look into the example programs.

SimpleDateFormat -  kk VS HH VS hh in Date Formatting Java


2. Understand kk VS HH vs hh in SimpleDateFormat

All of these 3 indicates the hours in date but there a little importance to know about each.

If you know the meaning of each one and what is range of values are considered then you are good with these formatters.

kk - hours - range (1 to 24) - hours in 24 hours format

HH - hours - range (0 to 23) - hours in 24 hours format

hh - hours - range (1 to 12) - hours in 12 hours format with AM/PM


3.  Example on kk VS HH VS hh 

let us write a simple program to understand each one and how it produces the date format.


package com.javaprogramto.java8.dates.format;

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

public class FormatDiffkkVShhVsHH {

	public static void main(String[] args) {

		// Creating the Date object
		Date date = new Date(2020, 12, 1, 00, 30, 30);
		System.out.println("Example date 1 : " + date);

		// Example with kk
		SimpleDateFormat formatkk = new SimpleDateFormat("kk:mm:ss");
		String kkValue = formatkk.format(date);
		System.out.println("Date Time format with kk : " + kkValue);

		// Example with HH
		SimpleDateFormat formatHH = new SimpleDateFormat("HH:mm:ss");
		String HHValue = formatHH.format(date);
		System.out.println("Date Time format with HH : " + HHValue);

		// Example with hh
		SimpleDateFormat formathh = new SimpleDateFormat("hh:mm:ss a");
		String hhValue = formathh.format(date);
		System.out.println("Date Time format with hh : " + hhValue);
	}
}
 

Output:

Example date 1 : Sat Jan 01 00:30:30 IST 3921
Date Time format with kk : 24:30:30
Date Time format with HH : 00:30:30
Date Time format with hh : 12:30:30 AM
 

We've taken hours value in the input is 00 means early morning.

But from the above output, you can see the difference clearly that kk printed hours value as 24, HH is taken as 11 and HH is 12 with AM.

Use the right one based on your need otherwise it will change the date time values completely.

4. Conclusion

In this article, we've seen what are the differences among kk, HH and hh date formats and example program with SimpleDateFormat.

GitHub

Ref

How to display time in 24 hours format in java ?

Java Program To Display Time In 24-hour Format

1. Overview

In this tutorial, we'll learn how to display the current time in 24 hours format.

Java Program To Display Time In 24-hour Format


2. Java Program To Display Time In 24-hour Format


Follow the below steps to format the new Date() into 24 hours format.

Steps:

Step 1: Create the current date and time using new Date().
Step 2: Create date formatter using SimpleDateFormat with "kk:mm:ss"
Step 3: Next, call formatter.format() method to get the date in the 24 hours string format.
package com.javaprogramto.java8.dates.format;

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

public class FormatTIme24HoursExample {

	public static void main(String[] args) {

		// Getting the current date and time
		Date currentDate = new Date();
		
		// Creating simple date formatter to 24 hours
		SimpleDateFormat formatter = new SimpleDateFormat("kk:mm:ss");
		
		// getting the time in 24 hours format
		String timeIn24Hours = formatter.format(currentDate);
		
		// printing the time
		System.out.println("Current time in 24 hours format : "+timeIn24Hours);
	}
}
 
Output:
Current time in 24 hours format : 21:19:26
 
In the above program, we can use the "HH:mm:ss" instead of "kk:mm:ss". But the main difference between kk and HH is k indicates hours from 1 to 24 where as H indicates hours in rage 0-23. Midnight indicates by k as 24 and H as 0.

3. Conclusion


In this quick article, we've seen how to display the time in 24 hours format.

How To Create A Thread Using Lambda Expressions In Java 8 and Using Runnable With Lambda?

 1. Overview

In this tutorial, we'll learn how to create a thread using lambda expression in java 8 and beyond versions.

Lambda expressions are newly added concept in the JDK 1.8 version and that introduced the functional programming concepts such as assigning the method to the variable.

Important point is that we can directly implementation for the abstract method of interface with java 8 lambda instead of overriding the method by implementing the interface.

How To Create A Thread Using Lambda Expressions In Java 8?


2. Example To Create New Thread Via Runnable Using Lambda in Java 8

In the below program, we are going to create the Thread and implementing the Runnable interface run() method using Lambda Expression.

By using Lambda, we can skip the implements Runnable interface and overriding the run() method which holds the core thread logic.

If you are new to java 8 lambda, you can read the complete set of rules to Lambda Expressions.

And also we can avoid new Runnable() and implementing the run() method using lamdba. Because, once you start writing the code using java 8 then compiler knows that you are using Function Interface Runnable which has only run() method.

So when you pass Runnable lambda to Thread constructor, it treats as passing implementation of Runnable interface with run() method.

Next, Look at the below example program to create a java thread via runnable using lambda expression


package com.javaprogramto.threads.java8;

public class CreateThreadLambda {

	public static void main(String[] args) {

		// Thread creation using java 8 lambda using runnable
		Thread evenNumberThread = new Thread(() -> {
			
			// this logic is implementation of run() method to print only even numbers
			for (int i = 0; i < 20; i++) {
				if (i % 2 == 0) {
					System.out.println("Even Number Thread : "+i);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});

		// starting the thread
		evenNumberThread.start();
		
		// Printing the odd numbers from main thread.
		for (int i = 0; i < 20; i++) {
			if (i % 2 == 1) {
				System.out.println("Odd Number Thread : "+i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
 

Output:

Even Number Thread : 0
Odd Number Thread : 1
Odd Number Thread : 3
Even Number Thread : 2
Odd Number Thread : 5
Even Number Thread : 4
Even Number Thread : 6
Odd Number Thread : 7
Odd Number Thread : 9
Even Number Thread : 8
Odd Number Thread : 11
Even Number Thread : 10
Odd Number Thread : 13
Even Number Thread : 12
Even Number Thread : 14
Odd Number Thread : 15
Even Number Thread : 16
Odd Number Thread : 17
Even Number Thread : 18
Odd Number Thread : 19
 

3. Conclusion

In this article, we've seen how to create a new thread using lambda java 8 with example program to print even and odd number in unordered.

GitHub

Runnable API

Creating a thread using Thread class and Runnable Interface

Function Interface in Java with Examples (apply() and Chain Methods andThen(), identity())

1.Introduction


In this tutorial, You'll learn how to use Function in Java 8 and Function Examples. This is part of core Functional Interfaces in Java 8 new concepts.

This is added as part of java 8 in java.util package.

Java 8 Function Examples (apply() and Chain Methods andThen(), identity())


Function interface is mainly useful if a method takes some input and produces output always.

First, Understand how it is implemented internally and how this Function can be leveraged in real-time applications.


2. Java 8 Function<T, R> Internal Implementation


First, Look at the below internal code how it is declared and provided an implementation in the default methods.

API Note: Represents a function that accepts one argument and produces a result.


You can define in the interface default methods which have a body. These are introduced in Java 8.

Observer the code and it needs two types T and R. And also it as a one functional method R apply(T t) which means it takes one input argument and returns a value.

Where T and R defined as follows.

T --> What is the input type
R --> What type of value is returned.     

[package java.util.function;
import java.util.Objects;

@FunctionalInterfacepublic interface Function<T, R> {
 
    R apply(T t);
 
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
 
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
 
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}]


And also this has two default and one static additional to the apply() method.

apply() method is called as Functional Method.

3. Java 8 Function<T, R> Example to convert Integer to String and Calculate String length

Function Examples:

package com.javaprogramto.java8.functional.interfaces.function;

import java.util.function.Function;

public class java8FunctionExample {

    public static void main(String[] args) {

        Function<String, Integer> function = str -> str.length();

        int length = function.apply("Hello world");
        System.out.println("Fucntion to find string length :" + length);

        Function<Integer, String> function2 = number -> String.valueOf(number) + " is now String";

        String output = function2.apply(1260);
        System.out.println("Funtion to covnert Integer to String : "+output);
    }
}

Output:

[Fucntion to find string length :11
Funtion to covnert Integer to String : 1260 is now String]

4. Java 8 Function<T, R> Example to convert Employee to String

Function Examples:

Employee.java

package com.javaprogramto.models;

public class Employee {

    private int id;
    private String fullName;
    private int age;

    public Employee(int id, String fullName, int age) {
        this.id = id;
        this.fullName = fullName;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", fullName='" + fullName + '\'' +
                ", age=" + age +
                '}';
    }
}


Function Examples Main Program:

package com.javaprogramto.java8.functional.interfaces.function;

import com.javaprogramto.models.Employee;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class EmployeeFuntionEample {

    public static void main(String[] args) {

        Function<Employee, String> empString = employee -> employee.getAge() + " - " + employee.getFullName();

        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee(100, "Jhon Paul", 25));
        list.add(new Employee(101, "Narmad Rao", 30));

        for (Employee emp : list) {
            String empInStr = empString.apply(emp);
            System.out.println(empInStr);
        }

    }
}

Output:

[25 - Jhon Paul
30 - Narmad Rao]

5. Java 8 Function<T, R> Example to convert List<Employee> to Map<Integer, Employee>

Function Examples:


package com.javaprogramto.java8.functional.interfaces.function;

import com.javaprogramto.models.Employee;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class FunctionListToMap {

  static Logger logger = LoggerFactory.getLogger(FunctionListToMap.class);

    public static void main(String[] args) {
        BasicConfigurator.configure();

        // Createing a list        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee(100, "Jhon Paul", 25));
        list.add(new Employee(101, "Narmad Rao", 30));

        // Creating Function to convert List to Map.        Function<List<Employee>, Map<Integer, Employee>> listToMap = employees -> {

            Map<Integer, Employee> newMap = new HashMap<>();
            for (Employee e : employees
            ) {
                newMap.put(e.getId(), e);
            }
            return newMap;
        };

        Map<Integer, Employee> empMap = listToMap.apply(list);
        logger.info("List to Map : " + empMap);
    }
}

Output:

[List to Map : {100=Employee{id=100, fullName='Jhon Paul', age=25}, 101=Employee{id=101, fullName='Narmad Rao', age=30}}]

6. Java 8 Function<T, R> chain(), andThen(), identity() Method Examples



Function<T,T> identity() : This is a static method and returns a function that always returns its input argument.
Function andThen(Function after): This is a default method and will be invoked after the current Function apply() method execution.

identity() example to find the first non-repeated character.

Function Examples:

You'll get a better understanding once you see the below example program.

package com.javaprogramto.java8.functional.interfaces.function;

import com.javaprogramto.models.Employee;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FunctionMethodExamples {

    public static void main(String[] args) {

        Function<Employee, String> empToStringFunction = emp -> emp.getFullName();

        Function<String, Integer> stringToIntFunction = str -> str.length();

        Function<Integer, Integer> squereFunction = numner -> numner * numner;

        // chain() method example        Integer squere = empToStringFunction.andThen(stringToIntFunction).andThen(squereFunction).apply(new Employee(500, "Lady Gaga", 50));

        System.out.println("andThen() example to get Employee name length squere : " + squere);

        // identity() example        String input = "aaaaa bbbbb";
        Map chars = input.codePoints().mapToObj(cp -> cp)
                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));

        System.out.println("identity chars "+chars);
    }


}

Output:

[andThen() example to get Employee name length squere : 81
identity chars {97=5, 32=1, 98=5}]

7. Conclusion


In conclusion, You've seen the example programs on Function Functional Interface.

And also have seen examples to find the repeated characters count in a string.

Finally, Examples to convert Integer to String, List to Map, and at last find the string length.

All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.


If you have any queries please post in the comment section.

Top Git Commands With Examples - Developer Uses Everyday

1. Introduction


In this tutorial, You'll learn what are the git commands that can be used in everyday life. You'll see the top git commands with examples. You can not imagine a developer's life without using version control tools such as git, bitbucket, or any tool.

Because this makes like simple and easy to maintain the programming files and collaborate with your teammates.

Most of you do not use git commands either you use GUI plugins in IDE eclipse or Intelleji tools

But, if you know all these handy command and you will get confidence in dealing with the conflicts resolving manually from the terminal.

Top Git Commands With Examples


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.


Java 8 – Convert date and time between timezone

1. Overview

In this tutorial, We'll learn how to convert date and time between timezone  using new java 8 date time api.

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.

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

2. Java 8 and Beyond Flight Timing TimeZone Conversion


Example program to convert IST time to PST and PST to GST adding 24 hours 20 mins.

How to create a simple 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 almost 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 understanding because of timezone change.

Look at the below example code that shows the exact arrival time after adding 24 hours and 20 mins to the start time with java 8 date time api. 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.between().
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
 

3. Conclusion


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