code:
package com.soofound.framework.util; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; /** * 设置时区 * * @author zxf * @date 2015-11-4 */ // java -classpath . com.linux.test.base.SetTimeZone public class SetTimeZone { public static void main(String[] args) { setTimeZone(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time1 = df.format(Calendar.getInstance().getTime()); System.out.println(time1); } /** * 设置时区 <br> * * 注:xx:59:59时,可能有问题。可以循环2次验证后再设置 */ public static void setTimeZone() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH"); String time = df.format(Calendar.getInstance().getTime()); /** * 如果当前java获取的时间与linux的'date'命令获取的时间一致,则不修改时区 */ String osTime = time(); System.out.println("def java time: " + time + ", os time: " + osTime); if ( time.equals(osTime) ) { return; } /** * 先获取往前减的时区 */ TimeZone correct = getCorrect("GMT-%d");// 如: GMT-8 () /** * 往前减的时区没有,则获取往后加的时区 */ if ( correct == null ) { correct = getCorrect("GMT+%d");// 如: GMT+8 } /** * 如果找到正确的时区,则设置为默认时区 */ if ( correct != null ) { System.out.printf("set TimeZone: %s %n", correct.getID()); osTime = time(); SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH"); String time1 = df1.format(Calendar.getInstance().getTime()); System.out.println("set . java time: " + time1 + ", os time: " + osTime); TimeZone.setDefault(correct); } } /** * 时区区间:1-16,一般1-12就可以了 * * @param format * @return */ private static TimeZone getCorrect(String format) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH"); for ( int i = 1; i <= 16; i++ ) { String tzName = String.format(format, i);// 减 | 加 TimeZone tz = TimeZone.getTimeZone(tzName); df.setTimeZone(tz); String time = df.format(Calendar.getInstance().getTime()); String linexTime = time(); if ( time.equals(linexTime) ) { return tz; } } return null; } /** * 获取系统时间 * * @return */ private static String time() { try { String cmd = "date '+%F %H'"; Process pro = Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd }); InputStream is = pro.getInputStream(); byte[] bs = new byte[1024]; int len = is.read(bs, 0, 1024); String time = new String(bs, 0, len); if ( time != null ) time = time.trim(); return time; } catch ( IOException e ) { return null; // return "2015-11-04 19";// windows test } catch ( Exception e ) { e.printStackTrace(); return null; } } }