How can I set the System Time in Java?
Java doesn't have an API to do this.
Most system commands to do it require admin rights, so Runtime
can't help unless you run the whole process as administrator/root or you use runas
/sudo
.
Depending on what you need, you can replace System.currentTimeMillis()
. There are two approaches to this:
Replace all calls to
System.currentTimeMillis()
with a call to a static method of your own which you can replace:public class SysTime { public static SysTime INSTANCE = new SysTime(); public long now() { return System.currentTimeMillis(); } }
For tests, you can overwrite INSTANCE with something that returns other times. Add more methods to create
Date
and similar objects.If not all code is under your control, install a
ClassLoader
which returns a different implementation forSystem
. This is more simple than you'd think:@Override public Class<?> loadClass( String name, boolean resolve ) { if ( "java.lang.System".equals( name ) ) { return SystemWithDifferentTime.class; } return super.loadClass( name, resolve ); }
One way would be using native commands.
for Windows, two commands (date and time) are required:
Runtime.getRuntime().exec("cmd /C date " + strDateToSet); // dd-MM-yy
Runtime.getRuntime().exec("cmd /C time " + strTimeToSet); // hh:mm:ss
for linux, a single command handles both date and time:
Runtime.getRuntime().exec("date -s " + strDateTimeToSet); // MMddhhmm[[yy]yy]
Update after 9 year
This is not a good way to set the time of system instead of that use java.util.Clock
to get the current time and provide mock implementation wherever needed to fake out the time.