Thursday, July 21, 2016

Java convert time zones

Yes, Java time (before Java 8) is a pain. Java 8 totally redo this but I am still at Java 7... and of course no time to learn it. People have been struggling for years for its foolishness with the Calendar object and stuff.

And if you deal with international things... timezone difference is going to be a headache. The world does not do day light savings time on the same day also.

Here is a great little util to convert between time zones... from String to String.


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Testing {
    private static String convertTimeZone(String datetime, String fmt, 
String timeZoneFrom, String timezoneTo) throws Exception {
     TimeZone defaultTimeZone = TimeZone.getDefault(); // save your default time zone
     TimeZone.setDefault(TimeZone.getTimeZone(timeZoneFrom));
                   
        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
        Date d = sdf.parse(datetime);

        sdf.setTimeZone(TimeZone.getTimeZone(timezoneTo));

        String result= sdf.format(d);
     TimeZone.setDefault(defaultTimeZone); // reset default time zone back
        return result;
       
    }

   public static void main(String arg[]) {
     try {
      System.out.println(convertTimeZone("2016-08-21 18:50:00",
"yyyy-MM-dd HH:mm:ss","UTC","Asia/Hong_Kong"));
      System.out.println(convertTimeZone("2016-08-21 06:50:00",
"yyyy-MM-dd HH:mm:ss","Europe/London","UTC"));
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
Check out time zone strings around the world. https://www.mkyong.com/java/java-display-list-of-timezone-with-gmt/.

No comments: