您的位置:首页 > 运维架构 > Linux

java修改操作系统时间(linux和windows)

2015-08-06 17:38 197 查看
import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

import java.util.TimeZone;

import org.junit.Test;

public class TestModifySysDate {

@Test

public void getSysdate1(){

DateFormat chinaFormatter=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM,Locale.CHINA);

DateFormat defaultFormatter=DateFormat.getDateTimeInstance();

Date now=new Date();

DateFormat gmt08Formatter=DateFormat.getDateTimeInstance();

TimeZone timezone=TimeZone.getTimeZone( “GMT 08:00 “);

gmt08Formatter.setTimeZone(timezone); //格式日期/时间

String defaultDateTime=defaultFormatter.format(now);

String chinaDateTime=chinaFormatter.format(now);

String gmt08DateTime=gmt08Formatter.format(now);

System.out.print( defaultDateTime+” ” +chinaDateTime+” “+ gmt08DateTime);

}

@Test
//修改window7时间
public void modifyTime(){
try {
Process p = Runtime.getRuntime().exec("cmd /c time 08:55:00");
//   p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

if (!br.ready()) {
Thread.sleep(100);
}
while (true) {
String s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}

@Test
//修改windows7日期
public void modifyDate(){
String date="2015-06-15";
try{
Runtime run=Runtime.getRuntime();
String command="cmd.exe /c date"+" "+(date);
run.exec(command);
}
catch(Exception e)
{
e.printStackTrace();
}
}
//linux下修改时间和日期


public static void main(String args[]) throws Exception{

FileWriter excutefw = new FileWriter(“/usr/updateSysTime.sh”);

BufferedWriter excutebw=new BufferedWriter(excutefw);

excutebw.write(“date -s \”2015-12-01 00:00:00\”\r\n”);

excutebw.write(“clock -w”);

excutebw.close();

excutefw.close();

String cmd_date =”sh /usr/updateSysTime.sh”;

Runtime.getRuntime().exec(cmd_date);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: