使用java设置系统时间的毫秒数

时间:2015-11-10 09:48:29

标签: java windows time command-line process

是否可以使用Java在Windows操作系统上设置毫秒组件的系统时间? 我试图在几台计算机之间同步时钟,但OS API似乎只提供格式的设置时间: HH:MM:SS

这是我试过的:

public static void main(String[] args) throws InterruptedException, IOException {


    String time="10:00:20"; // this works

    String timeWithMiliseconds = "10:00:20.100"; // this doesn't change time at all

    Runtime rt = Runtime.getRuntime();
    rt.exec("cmd /C time " + time);


}

我想知道如果NTP客户端无法设置毫秒组件,它们如何工作?

解决此问题的一种方法可能是计算服务器应达到下一秒的时间(以毫秒为单位),并在此时间内休眠。是否有更好,更直接的方法来实现这一目标?

1 个答案:

答案 0 :(得分:2)

正如immibis所提到的,您可以使用Windows函数SetSystemTime来设置时间。

在下面找到使用JNA 4.2

调用Windows函数的代码段
Kernel32 kernel = Kernel32.INSTANCE;
WinBase.SYSTEMTIME newTime = new WinBase.SYSTEMTIME();
newTime.wYear = 2015; 
newTime.wMonth = 11;
newTime.wDay = 10;
newTime.wHour = 12;
newTime.wMinute = 0;
newTime.wSecond = 0;
newTime.wMilliseconds = 0;
kernel.SetSystemTime(newTime);

有关详细信息,请查看JNA的来源以及这些链接 SetSystemTime Windows functionSYSTEMTIME structure

2009年JNA简介。Simplify Native Code Access with JNA