简体   繁体   English

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

[英]Setting milliseconds of System time with java

Would it be possible to set system time with milliseconds component on Windows OS using Java? 使用Java在Windows操作系统上是否可以用毫秒为单位设置系统时间? I am trying to synchronize clocks between couple of computers but the OS API seems to offer only set time in format: HH:MM:SS . 我正在尝试在几台计算机之间同步时钟,但OS API似乎仅提供以下格式的设置时间: HH:MM:SS

This is what i tried: 这是我尝试的:

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


}

I am wondering how do NTP clients work if it's not possible to set milliseconds component ? 我想知道如果无法设置毫秒组件,NTP客户端如何工作?

One way to deal with this issue could be to calculate time in milliseconds when server should reach next second, and sleep for that time. 解决此问题的一种方法可能是计算服务器应该到达下一秒的时间(以毫秒为单位),然后休眠该时间。 Is there a better, more direct way to achieve this ? 有没有更好,更直接的方法来实现这一目标?

As mentioned by immibis you could use the Windows function SetSystemTime to set the time. 如immibis所述,您可以使用Windows函数SetSystemTime来设置时间。

Find below a snippet which call the Windows function using JNA 4.2 在下面找到一个使用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);

For further information have a look into the sources of JNA and on those links SetSystemTime Windows function and SYSTEMTIME structure . 有关更多信息,请查看JNA的源代码以及SetSystemTime Windows函数SYSTEMTIME结构的那些链接。

An introduction to JNA from 2009. Simplify Native Code Access with JNA 2009年开始介绍JNA。 使用JNA简化本机代码访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM