java 修改时区_java改时区

packagecom.soofound.framework.util;importjava.io.IOException;importjava.io.InputStream;importjava.text.SimpleDateFormat;importjava.util.Calendar;importjava.util.TimeZone;/*** 设置时区

*

*@authorzxf

* @date 2015-11-4*/

//java -classpath . com.linux.test.base.SetTimeZone

public classSetTimeZone {public static voidmain(String[] args) {

setTimeZone();

SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String time1=df.format(Calendar.getInstance().getTime());

System.out.println(time1);

}/*** 设置时区

*

* 注:xx:59:59时,可能有问题。可以循环2次验证后再设置*/

public static voidsetTimeZone() {

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就可以了

*

*@paramformat

*@return

*/

private staticTimeZone 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) ) {returntz;

}

}return null;

}/*** 获取系统时间

*

*@return

*/

private staticString 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();returntime;

}catch( IOException e ) {return null;//return "2015-11-04 19";//windows test

} catch( Exception e ) {

e.printStackTrace();return null;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值