wangmengmeng
2025-04-26 96250617dbbefce55b5966c94880e2b07b6c98df
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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();
        }
    }
 
}