如何在 Java 中设置系统时间? [英] How can I set the System Time in Java?

查看:124
本文介绍了如何在 Java 中设置系统时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Java 中更改系统时间?

Is it possible to change the System Time in Java?

它应该可以在 Windows 和 Linux 下运行.我已经在 Runtime 类中尝试过,但是权限有问题.

It should run under Windows and Linux. I've tried it with the Runtime Class in but there is a problem with the permissions.

这是我的代码:

String cmd="date -s ""+datetime.format(ntp_obj.getDest_Time())+""";
try {
    Runtime.getRuntime().exec(cmd);
} catch (IOException e1) {
// TODO Auto-generated catch block
  e1.printStackTrace();
}
System.out.println(cmd);

cmd 的输出是:

date -s "06/01/2011 17:59:01"

但是系统时间和之前一样.

But the System time is the same as before.

我将设置时间,因为我正在编写 NTP 客户端,然后我从 NTP 服务器获取时间并进行设置.

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

推荐答案

Java 没有执行此操作的 API.

Java doesn't have an API to do this.

执行此操作的大多数系统命令都需要管理员权限,因此 Runtime 无法提供帮助,除非您以管理员/root 身份运行整个过程或使用 runas/sudo.

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.

根据您的需要,您可以替换System.currentTimeMillis().有两种方法可以解决这个问题:

Depending on what you need, you can replace System.currentTimeMillis(). There are two approaches to this:

  1. 将所有对 System.currentTimeMillis() 的调用替换为对您自己的静态方法的调用,您可以替换该方法:

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

对于测试,您可以使用其他时间返回的内容覆盖 INSTANCE.添加更多方法来创建 Date 和类似的对象.

For tests, you can overwrite INSTANCE with something that returns other times. Add more methods to create Date and similar objects.

如果并非所有代码都在您的控制之下,请安装一个 ClassLoader,它会为 System 返回不同的实现.这比您想象的要简单:

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:

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

    return super.loadClass( name, resolve );
}

这篇关于如何在 Java 中设置系统时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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