有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

是否可以使用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) 个答案

  1. # 1 楼答案

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