Java 8– Calculate date & time difference between two Zone


In Java 8, we can use LocalDateTime.now(ZoneId.of(String zoneId)) to get current LocalDateTime instance of the zoneId  and Duration to calculate the difference between two LocalDateTime.

Similar Posts:

Java8ZoneDiff.java
package org.websparrow;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class Java8ZoneDiff {

	public static void main(String[] args) {

		// Current date & time of India
		LocalDateTime india = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));

		// Current date & time of Thailand
		LocalDateTime thailand = LocalDateTime.now(ZoneId.of("Asia/Bangkok"));

		System.out.println("Thailand current date & time: " + thailand);
		System.out.println("India current date & time: " + india);
		System.out.println("\n================  Difference  ================\n");

		Duration diff = Duration.between(india, thailand);

		// days between Thailand and India
		System.out.println("Days: " + diff.toDays());

		// hours between Thailand and India
		System.out.println("Hours: " + diff.toHours());

		// Minutes between Thailand and India
		System.out.println("Minutes: " + diff.toMinutes());

		// Seconds between Thailand and India
		System.out.println("Seconds: " + diff.getSeconds());

	}
}
Console
Thailand current date & time: 2020-07-02T22:55:08.968
India current date & time: 2020-07-02T21:25:08.968

================  Difference  ================

Days: 0
Hours: 1
Minutes: 90
Seconds: 5400

References

  1. Java 8 – Calculate difference between two LocalDateTime
  2. How to calculate difference between two dates in Java
  3. Class LocalDateTime
  4. Class Duration
  5. Class ZoneId

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.