0

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

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

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

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.

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

EDIT:

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

Runtime.getRuntime().exec(new String[]{ "sudo", "date", "--set", newTime })
MarcioB
  • 1,538
  • 1
  • 9
  • 11

1 Answers1

1

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

Runtime.getRuntime().exec(new String[]{ "date", "--set", "2014-08-01 11:53:17" });
Sid
  • 1,144
  • 10
  • 21
  • 2
    @MarcioB You need to check whether some sort of error is being produced. The `.exec()` method returns a `Process` object. You need to access this object's input, output and error streams. See this link which shows you how to access the `OutputStream` and `InputStream`: http://stackoverflow.com/questions/3936023/printing-runtime-exec-outputstream-to-console. You can take a similar approach to get the `ErrorStream` – Sid Aug 01 '14 at 14:50
  • I did exactly that, look at my comment on the question. – MarcioB Aug 01 '14 at 14:54
  • @MarcioB Okay. Have you tried executing some other shell command? Do they work? – Sid Aug 01 '14 at 15:00
  • Yes, the method resetTime(), that is on the question, works fine. – MarcioB Aug 01 '14 at 15:07
  • I was looking at the wrong output. You are right, I should a String[], but where do I put the "sudo" in the array? – MarcioB Aug 01 '14 at 18:35
  • 1
    @MarcioB So I guess running it without adding the `sudo` doesn't work. Try running the entire program with a user that has `sudo`. If that doesn't work then you can also try: `new String[]{ "sudo date", "--set"...` or `new String[]{ "sudo", "date", "--set"...`. – Sid Aug 01 '14 at 19:06