1.依赖
<dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.9.0</version></dependency>2.publicvoidupdataSystemDate(IotTimeSynchronization iotTimeSynchronization)throwsIOException{// String ntpServer = "time.windows.com";String ntpServer = iotTimeSynchronization.getSysServer();int timeout =10000;// 超时时间设置为10秒NTPUDPClient client =newNTPUDPClient();try{// 设置超时时间
client.setDefaultTimeout(timeout);// 获取NTP服务器的InetAddress对象InetAddress hostAddr =InetAddress.getByName(ntpServer);// 打开连接并获取时间信息TimeInfo info = client.getTime(hostAddr);// 等待响应
info.computeDetails();long returnTime = info.getMessage().getTransmitTimeStamp().getTime();Date time =newDate(returnTime);String formatDateTime =DateUtil.formatDateTime(time);// String dateTime = "2024-12-13 13:12:11";SystemTimeSetterUtil.setTime(formatDateTime);}catch(Exception e){
e.printStackTrace();}}3.工具类
importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.nio.charset.Charset;publicclassSystemTimeSetterUtil{publicstaticvoidsetTime(String dateTime)throwsIOException,InterruptedException{String osName =System.getProperty("os.name").toLowerCase();if(osName.contains("win")){setWindowsTime(dateTime);}elseif(osName.contains("nix")|| osName.contains("nux")|| osName.contains("mac")){setLinuxTime(dateTime);}else{thrownewUnsupportedOperationException("Unsupported operating system.");}}privatestaticvoidsetLinuxTime(String dateTime)throwsIOException,InterruptedException{// Linux command to set date and time. Requires sudo or root privileges.String[] command ={"sudo","date","--set", dateTime};executeCommand(command);}privatestaticvoidsetWindowsTime(String dateTime)throwsIOException,InterruptedException{// Split the dateTime into date and time for Windows commandsString datePart = dateTime.substring(0,10);String timePart = dateTime.substring(11,19);// Windows command to set date and time. Requires admin privileges.String setDateCmd =String.format("cmd /c date %s", datePart);String setTimeCmd =String.format("cmd /c time %s", timePart);executeCommand(setDateCmd.split(" "));executeCommand(setTimeCmd.split(" "));}privatestaticvoidexecuteCommand(String[] command)throwsIOException,InterruptedException{ProcessBuilder pb =newProcessBuilder(command);
pb.redirectErrorStream(true);Process process = pb.start();try(BufferedReader reader =newBufferedReader(newInputStreamReader(process.getInputStream(),Charset.forName("UTF-8")))){String line;while((line = reader.readLine())!=null){System.out.println(line);}}int exitCode = process.waitFor();if(exitCode !=0){thrownewIOException("Command failed with exit code: "+ exitCode);}}publicstaticvoidmain(String[] args){try{// Example usage. Replace with your desired date and time.// The format should be compatible with the OS's date command.String dateTime ="2024-12-13 13:12:11";// For Linux// String dateTime = "12/13/2024 14:12:12"; // For WindowsSystem.out.println("Setting system time...");setTime(dateTime);System.out.println("System time has been set.");}catch(IOException|InterruptedException e){
e.printStackTrace();}}