gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:12:45 26 4
gpt4 key购买 nike

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

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

最佳答案

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

关于java - 用java设置系统时间的毫秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com