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

使用java设置系统时间的毫秒数,java,windows,time,command-line,process,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 timeWithMiliseco

是否可以使用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客户端如何工作


解决此问题的一种方法是计算服务器到达下一秒的时间(以毫秒为单位),并休眠该时间。有没有更好、更直接的方法来实现这一点?

如immibis所述,您可以使用Windows函数
SetSystemTime
来设置时间

在下面查找使用调用Windows函数的代码段

有关更多信息,请查看JNA的来源以及这些链接 及


2009年的JNA简介

因为他们不使用console命令来设置时间;他们可能会使用这个函数,而这个函数(和其他Windows函数一样)是您无法从Java轻松访问的。谢谢您的评论。因此,不可能使用ProcessBuilder/Runtime调用该函数,必须使用JNI?为什么不能直接使用NTP客户端?这只是我正在处理的一个分配,不允许这样做。要调用不属于Java(但属于C ish)的方法,必须使用JNI(或)。或者,您可以通过
运行时启动脚本/自定义exe,允许以毫秒精度设置时间
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);