出于测试目的,我需要改变的Linux系统时间。 我到目前为止已经做的是:
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR_OF_DAY, 2); //example of a 2 hour alteration
alterSystemTime(calendar.getTime().toString());
public void alterSystemTime(String newTime) {
Runtime.getRuntime().exec("sudo date -s \"" + newTime + "\"");
}
并重置一次,我打电话:
public void resetTime() {
Runtime.getRuntime().exec("sudo hwclock --hctosys");
}
正在执行的命令的一个例子在alterSystemTime方法是:
须藤日期-s“周五8月1日12点15分47秒BRT 2014”
当在终端上执行的,但不要对代码工作时,此工作正常。 我有等/ sudoers文件正确配置为不要求密码运行sudo命令。 在重新设定时间功能按预期工作。 我也试着日期解析到这样的格式化字符串:
sudo date -s "2014/08/01 11:53:17"
再次,适用于终端,但不会上节目。
那么,为什么我的方法alterSystemTime()不工作? 这是修改系统时间是正确的做法?
编辑:
基于Sid的答案,我用这个的方法:
Runtime.getRuntime().exec(new String[]{ "sudo", "date", "--set", newTime })