MarcioB
MarcioB

Reputation: 1568

How to Increment and Decrement time in Linux with Java

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

Upvotes: 0

Views: 542

Answers (1)

Sid
Sid

Reputation: 1144

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

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

Upvotes: 1

Related Questions