1. Getting all available time zone information in Java
String[] availableIDs = TimeZone.getAvailableIDs(); for (String string : availableIDs) { System.out.println(string); }
II. Time Zone Conversion
/*Asia/Bishkek*/ TimeZone timeZone = TimeZone.getTimeZone("Asia/Bishkek"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(timeZone); String format = sdf.format(Calendar.getInstance().getTime()); System.out.println(format); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); String format2 = sdf.format(new Date()); System.out.println(format2);
The output time of Kyrgyzstan and Beijing time are listed above. Here is the time zone for Beijing time, Asia/Shanghai.
Conversion between UTC time and local time
public static SimpleDateFormat get(){ return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); } public static String getUTCTime(){ /*Local time*/ Calendar instance = Calendar.getInstance(); /*Time zone difference*/ int i = instance.get(Calendar.ZONE_OFFSET); /*Summer time difference*/ int j = instance.get(Calendar.DST_OFFSET); instance.add(Calendar.MILLISECOND, -(i+j)); int year = instance.get(Calendar.YEAR); int month = (instance.get(Calendar.MONTH) + 1); int day = instance.get(Calendar.DAY_OF_MONTH); int hour = instance.get(Calendar.HOUR_OF_DAY); int minute = instance.get(Calendar.MINUTE); int second = instance.get(Calendar.SECOND); int milliSecond = instance.get(Calendar.MILLISECOND); try { String UTCTimeString = year + "-" + (month < 10 ? "0"+month : month) + "-" + day + " " + hour + ":" + minute + ":" + second + "." + milliSecond; get().parse(UTCTimeString); return UTCTimeString; } catch (ParseException e) { e.printStackTrace(); } return null; }
Through the above method, UTC time can be obtained.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String utcTime = getUTCTime(); System.out.println(utcTime); Date UTCDate = sdf.parse(utcTime); System.out.println(UTCDate); sdf.setTimeZone(TimeZone.getTimeZone("GMT-8"));//It should be noted here that this is the only way to do it. String format3 = sdf.format(UTCDate); System.out.println(format3);
In this way, UTC time can be converted to zero time, but it should be noted that when the transformation is done, the form of "GMT-8" can only be used, and the form of "Asia/Shanghai" does not work.