如何用Java增加和减少Linux中的时间 [英] How to Increment and Decrement time in Linux with Java

查看:142
本文介绍了如何用Java增加和减少Linux中的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了测试目的,我需要在Linux中改变系统时间。目前为止,我所做的是:

For testing purposes I need to alter the system time in Linux. What I've done so far is:

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 + "\"");
}

要重置我打电话的时间:

And to reset time I call:

public void resetTime() {
    Runtime.getRuntime().exec("sudo hwclock --hctosys");
}

在alterSystemTime方法中执行的命令的示例是:

An example of the command being executed in the alterSystemTime method is:


sudo date -sFri Aug 01 12:15:47 BRT 2014

sudo date -s "Fri Aug 01 12:15:47 BRT 2014"

在终端上执行时工作正常,但不对代码工作。我的etc / sudoers文件正确配置为运行一个sudo命令而不要求密码。 resetTime函数按预期工作。我也试图解析日期到一个形成的字符串,如下所示:

This works fine when executed on the Terminal, but don't work on the code. I have the etc/sudoers file properly configured to run a sudo command without asking for the password. The resetTime function works as expected. I also tried to parse the date to a formated String like this:

sudo date -s "2014/08/01 11:53:17"

再次,在终端上工作,但不在程序上。

which again, works on the Terminal but not on the program.

那么为什么我的方法alterSystemTime()不工作?这是否是改变系统时间的正确方法?

So, why my method alterSystemTime() is not working? Is this the right approach to alter the system time?

编辑:

根据Sid的答案,以下方法使用这个方法:

Based on Sid's answer, I've used this on the method:

Runtime.getRuntime().exec(new String[]{ "sudo", "date", "--set", newTime })


推荐答案

尝试传递一个String数组到 .exec()

Try passing in a String array to .exec():

Runtime.getRuntime().exec(new String[]{ "date", "--set", "2014-08-01 11:53:17" });

这篇关于如何用Java增加和减少Linux中的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆