0

I am using browser offset time to convert a given time to local time. Here is the code I am using for converting time from atlantic timezone(-4:00) to IST.

int hours=23;
int mins =30;
Calendar date=Calendar.getInstance();
date.set(Calendar.HOUR_OF_DAY, hours);
date.set(Calendar.MINUTE, mins);  
browserOffsetTime=-browserOffsetTime;
TimeZone defaultTZ=TimeZone.getTimeZone("Atlantic/Bermuda");
int serverTimeOffset=defaultTZ.getRawOffset()+defaultTZ.getDSTSavings();
Date GMTDate= new Date(date.getTimeInMillis() - serverTimeOffset);
Date userBrowserTime = new Date(GMTDate.getTime() + browserOffsetTime);
Calendar cal1=Calendar.getInstance();
cal1.setTime(userBrowserTime);

This code returns exact result for EST which is 10:00 AM where as it returns 8:00 AM which should be 9:00 AM.

https://stackoverflow.com/a/21349556/3739916 this code returns exact results for both the time zones. But I need to work this out using browser offset time.

Community
  • 1
  • 1
SwethaHarshini
  • 79
  • 1
  • 14

1 Answers1

1

You are making several common mistakes:

  • You've got a fixed offset that you obtained from the browser - probably through JavaScript code like new Date().getTimezoneOffset(). That would be the offset from UTC for the client at the current date and time. You cannot just apply this offset to any arbitrary timestamp, as the client's offset may be different depending on which point in time you are asking for. See "time zone != offset" in the timezone tag wiki, and see this answer for how to guess at the user's actual time zone.

  • You're doing a lot of manual manipulation of timestamps and offsets through addition and subtraction. This sort of code should be avoided unless you're authoring a date/time library. Java has many good options, such as Joda-Time for Java 7 and earlier, and the built-in java.time package for Java 8 and newer. You should avoid using the java.util.Date and java.util.Calendar APIs, as there are many challenges with these.

  • When you do something like new Date(timestamp + offset) - you aren't actually performing a time zone conversion. Everything that interacts with the java.util.Date object is expecting that the timestamp is based on the Unix Epoch, which is explicitly in terms of UTC (1970-01-01T00:00:00Z). So if you add or subtract an offset, you're just picking a different instant in time. If you use the newer APIs, you will not have to think about this.

  • You are computing serverTimeOffset as the base offset + the DST bias, but you aren't considering whether or not DST is in effect. If you use the newer APIs, you will not have to think about this either.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575