package com.dji.sample.component.ntp; import org.apache.commons.net.ntp.NTPUDPClient; import org.apache.commons.net.ntp.TimeInfo; import java.io.IOException; import java.net.InetAddress; import java.text.SimpleDateFormat; import java.util.Calendar; public class NTPClient { private static long localTime; private static long serverNTPTime; private static NTPUDPClient client; private static InetAddress host; public static void connect() { try { client = new NTPUDPClient(); client.open(); host = InetAddress.getByName("192.168.1.162"); } catch (Exception e) { e.printStackTrace(); } } public static void check() { try { TimeInfo timeInfo = client.getTime(host); serverNTPTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); localTime = System.currentTimeMillis(); long timeDiff = serverNTPTime - localTime; System.out.println("Server time: " + serverNTPTime); System.out.println("Local time: " + localTime); System.out.println("Time difference: " + timeDiff + " milliseconds"); if(timeDiff>1000){ try { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(serverNTPTime); // 设置系统时间为calendar表示的时间 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("win")) { Process process = Runtime.getRuntime().exec("cmd /c date " + format.format(calendar.getTime())); process.waitFor(); System.out.println("Windows操作系统"); } else { Process process = Runtime.getRuntime().exec("sudo -s date " + format.format(calendar.getTime())); process.waitFor(); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } // client.close(); } catch (Exception e) { e.printStackTrace(); } } }