Roy Tang

Programmer, engineer, scientist, critic, gamer, dreamer, and kid-at-heart.

Blog Notes Photos Links Archives About

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!

Comments

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

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));