1

I have two inputs:

  • a date value
  • an integer (+8 or -3 or such) that represents the offset from GMT

Using Java, how can I convert the given date value into the corresponding date/time in the local timezone? There doesn't seem to be any timezone offset function in the Date class.

Thanks!

Roy Tang
  • 5,643
  • 9
  • 44
  • 74

2 Answers2

1

(If you don't want to use JodaTime) Use TimeZone with setRawOffset with code from this answer: https://stackoverflow.com/a/19378721/360211

Community
  • 1
  • 1
weston
  • 54,145
  • 21
  • 145
  • 203
0

I think you need to use the TimeZone.getAvailableIDs(rawOffsetinMiliSeconds) to get a timezone value. Working Example:

Date now = new Date();  
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
sdf1.setTimeZone(TimeZone.getTimeZone("UTC"));  
System.out.println(sdf1.format(now));  
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
sdf2.setTimeZone(TimeZone.getTimeZone((TimeZone.getAvailableIDs(5*1000*3600))[0]));  
System.out.println(sdf2.format(now));  
Abs
  • 3,902
  • 1
  • 31
  • 30
  • A "time zone" and a "time zone offset" are two different things. Using this code will give you the *first* time zone that uses this offset, but that's not necessarily the correct time zone. – Matt Johnson-Pint Jun 02 '14 at 17:47
  • RTFQ He wants the "date/time in the local timezone" and not the timezone name of choice – Abs Jun 03 '14 at 06:11