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

Setting milliseconds of System time with java

是否可以使用 Java 在 Windows OS 上设置带毫秒分量的系统时间? 我正在尝试同步几台计算机之间的时钟,但 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 客户端如何工作?

处理此问题的一种方法是以毫秒为单位计算服务器应该到达下一秒的时间,并在该时间休眠。有没有更好、更直接的方法来实现这个目标?

正如 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