1

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Rahman
  • 3,755
  • 3
  • 26
  • 43
  • Where does "emp" come from? – Juan Jun 30 '17 at 04:19
  • `emp` is an obj reference of entity class `Employee` which is mapped to the table – Rahman Jun 30 '17 at 04:22
  • What would be the output of `emp.getModifiedDate().getTime();`? – Aakash Verma Jun 30 '17 at 04:24
  • The problem you have is that in millis it is the same time, because it is UTC based. The timezone is what gives the UTC time a local view. – Juan Jun 30 '17 at 04:56
  • I don’t think I understood the need for any conversion. A `Timestamp` is just a point in time, it’s the same in all time zones. If you can tell us the datatype of your database column and give us an example value and the requested result for that value (for some point in time in Israel Standard Time), we can probably help you a lot better (oops, was IST for Irish Summer Time? India Standard Time? those three letter abbreviations are extremely dangerous and quite confusing). – Ole V.V. Jun 30 '17 at 22:30

5 Answers5

4

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
3

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
clstrfsck
  • 14,715
  • 4
  • 44
  • 59
2

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.

Pallavi Sonal
  • 3,661
  • 1
  • 15
  • 19
  • Thanks for your help Pallavi but currently we are using java 1.5 – Rahman Jun 30 '17 at 09:17
  • 1.5, that’s old, @Rehman. Some 12 years old now. If there’s any chance you can upgrade to Java 6 (or later), you may use the [ThreeTen Backport](http://www.threeten.org/threetenbp/) and the above code. It’s a good answer. – Ole V.V. Jun 30 '17 at 22:20
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("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.

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

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);
user85421
  • 28,957
  • 10
  • 64
  • 87
  • Thanks for your response Carlos. But for both getOffset() and getRawOffset() , difference is returned as 10.5 hrs whereas the actual difference is 9.5 hrs between IST and EST – Rahman Jun 30 '17 at 09:20
  • That is expected, by [Wikipedia](https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations) EST is `UTC-05` and IST is UTC+5:30 - The problem is that EST does not include daylight saving time, that would be EDT, the correct one should be EST5EDT, for both cases . But by documentation using such abbreviation is not recommend, better use an ID as "US/Eastern" or "America/New_York". – user85421 Jun 30 '17 at 10:17
  • changed answer to reflect that and give result in hours instead of milliseconds – user85421 Jun 30 '17 at 10:22