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

查看:2018
本文介绍了如何在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.

执行此操作的大多数系统命令都需要管理员权限,因此除非您以管理员/ 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其他时间。添加更多方法来创建日期和类似对象。

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天全站免登陆