joen joen - 8 months ago 35
Java Question

How can I set the System Time in Java?

Is it possible to change the System Time in Java?

It should run under Windows and Linux. I've tried it with the

Class in but there is a problem with the permissions.


Hello and thanks,

Here is the code i have try:

String cmd="date -s \""+datetime.format(ntp_obj.getDest_Time())+"\"";
try {
} catch (IOException e1) {
// TODO Auto-generated catch block

The output of cmd is: date -s "06/01/2011 17:59:01"
But the System time is the same as before.

I will set the time because iam writing an NTP-Client and there i get the time from a NTP-Server and will set it.


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:

  1. 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.

  2. If not all code is under your control, install a ClassLoader which returns a different implementation for System. This is more simple than you'd think:

    public Class<?> loadClass( String name, boolean resolve ) {
        if ( "java.lang.System".equals( name ) ) {
            return SystemWithDifferentTime.class;
        return super.loadClass( name, resolve );