1

I want to calculate the time difference between two different timezones like country1 (GMT+05:30) and country2 (GMT+05:00). How to calculate it. Thanks in advance.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Anwar Zahid
  • 227
  • 3
  • 10

1 Answers1

2

You can find it using java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.

import java.time.Duration;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;

public class Main {

    public static void main(String[] args) {
        // Test
        System.out.println(formatDuration(diffBetweenTimeZones("GMT+05:30", "GMT+05:00")));
        System.out.println(formatDuration(diffBetweenTimeZones("GMT+05:00", "GMT+05:30")));

        // You can use the returned value to get the ZoneOffset which you can use for
        // various kinds of processing e.g.
        ZoneOffset offset = ZoneOffset.of(formatDuration(diffBetweenTimeZones("GMT+05:30", "GMT+05:00")));
        System.out.println(offset);
        System.out.println(OffsetDateTime.now(offset));
    }

    static Duration diffBetweenTimeZones(String tz1, String tz2) {
        LocalDate today = LocalDate.now();
        return Duration.between(today.atStartOfDay(ZoneId.of(tz1)), today.atStartOfDay(ZoneId.of(tz2)));
    }

    static String formatDuration(Duration duration) {
        long hours = duration.toHours();
        long minutes = duration.toMinutes() % 60;
        String symbol = hours < 0 || minutes < 0 ? "-" : "+";
        return String.format(symbol + "%02d:%02d", Math.abs(hours), Math.abs(minutes));

        // ####################################Java-9####################################
        // return String.format(symbol + "%02d:%02d", Math.abs(duration.toHoursPart()),
        // Math.abs(duration.toMinutesPart()));
        // ####################################Java-9####################################
    }
}

Output:

+00:30
-00:30
+00:30
2021-03-24T10:37:31.056405+00:30

Learn more about the modern date-time API from Trail: Date Time.

Note that the java.util date-time API is outdated and error-prone. It is recommended to stop using it completely and switch to the modern date-time API*.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110