Rahman
Rahman

Reputation: 3785

Time Difference of two different timezone

I want to get the difference of current time (Which is IST) and the time which is stored in DB(EST). In order to that I am trying to convert current time to EST before calculating the difference. But its not working. In the following approach, local time is not getting converted to EST only. Could you please suggest me the better way to do it ? The return type of getModifiedDate is java.sql.Timestamp and the data type of the column is DATE

Code :

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("EST"));
 cal.setTimeInMillis(System.currentTimeMillis());
 cal.getTimeInMillis() - emp.getModifiedDate().getTime();

I was trying to do it using SimpleDateFormat , But I am not sure how to proceed with that approach.

If you can provide the code snippet that will be helpful

Upvotes: 1

Views: 5539

Answers (5)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

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("Asia/Kolkata", "America/New_York")));
        System.out.println(formatDuration(diffBetweenTimeZones("America/New_York", "Asia/Kolkata")));

        // You can use the returned value to get the ZoneOffset which you can use for
        // other processing e.g.
        ZoneOffset offset = ZoneOffset.of(formatDuration(diffBetweenTimeZones("Asia/Kolkata", "America/New_York")));
        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:

+09:30
-09:30
+09:30
2021-03-24T19:52:29.474858+09: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.

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

You can try java.util.TimeZone

    long now = System.currentTimeMillis();
    long diff = TimeZone.getTimeZone("IST").getOffset(now) - TimeZone.getTimeZone("EST").getOffset(now); 

getOffset - Returns the offset of this time zone from UTC at the specified date

Upvotes: 4

user85421
user85421

Reputation: 29680

TimeZone has two methods getRawOffet and getOffset that retrieves the offset of the time zone to UTC in milliseconds. The second one is adjusted for Daylight Saving Time and request the date to check if it is in effect.

TimeZone current = TimeZone.getDefault();
TimeZone db = TimeZone.getTimeZone("US/Eastern");  // or "EST5EDT", or "America/New_York"
System.out.printf("DB: %s    Current: %s\n", db, current);

System.out.printf("Raw: %.1f h\n", (db.getRawOffset() - current.getRawOffset())/3_600_000D);

final long now = System.currentTimeMillis();
System.out.printf("DST: %.1f h\n", (db.getOffset(now) - current.getOffset(now))/3_600_000D);

Upvotes: 0

clstrfsck
clstrfsck

Reputation: 14829

If you have access to Java 8, then it may be just as easy to calculate the difference between the two dates directly, rather than adjusting to a target time zone first.

You could do this using ZonedDateTime from the java.time package:

// Our timestamp
Timestamp ts = emp.getModifiedDate();

// Convert timestamp to ZonedDateTime in the correct time zone
ZonedDateTime estTime = ts.toLocalDateTime().atZone(ZoneId.of("America/New_York"));

// Could pass in ZoneId.of("Asia/Kolkata") argument to now(...), but not required
// as "now" is the same instant in all time zones.
ZonedDateTime zonedNow = ZonedDateTime.now();

// Can use other ChronoUnit values if required.
long timeDiff = ChronoUnit.MILLIS.between(zonedNow, estTime);

// Use timeDiff as required

Upvotes: 3

Pallavi Sonal
Pallavi Sonal

Reputation: 3901

I suggest using the java.time API of JDK 8 which simplifies this to a great extent. Consider the following example:

Timestamp t = emp.getModifiedDate();
Duration.between(t.toInstant(), ZonedDateTime.now(ZoneId.of("Asia/Kolkata")).toInstant());

The timestamp retrieved from DB has been converted to Instant which is in UTC, similarly the current time in Asia/Kolkata zone has been converted to Instant and the Duration between the two has been calculated.You can retrieve the required information from the duration.

Upvotes: 2

Related Questions