设置系统时间功能

1.依赖
      <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.9.0</version>
        </dependency>
2.        public void updataSystemDate(IotTimeSynchronization iotTimeSynchronization) throws IOException {

//        String ntpServer = "time.windows.com";
        String ntpServer = iotTimeSynchronization.getSysServer();
        int timeout = 10000; // 超时时间设置为10秒
        NTPUDPClient client = new NTPUDPClient();
        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 = new Date(returnTime);

            String formatDateTime = DateUtil.formatDateTime(time);
//        String dateTime = "2024-12-13 13:12:11";
        SystemTimeSetterUtil.setTime(formatDateTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    3.工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class SystemTimeSetterUtil {

    public static void setTime(String dateTime) throws IOException, InterruptedException {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            setWindowsTime(dateTime);
        } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
            setLinuxTime(dateTime);
        } else {
            throw new UnsupportedOperationException("Unsupported operating system.");
        }
    }

    private static void setLinuxTime(String dateTime) throws IOException, InterruptedException {
        // Linux command to set date and time. Requires sudo or root privileges.
        String[] command = {"sudo", "date", "--set", dateTime};
        executeCommand(command);
    }

    private static void setWindowsTime(String dateTime) throws IOException, InterruptedException {
        // Split the dateTime into date and time for Windows commands
        String 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(" "));
    }

    private static void executeCommand(String[] command) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        Process process = pb.start();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("UTF-8")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IOException("Command failed with exit code: " + exitCode);
        }
    }

    public static void main(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 Windows

            System.out.println("Setting system time...");
            setTime(dateTime);
            System.out.println("System time has been set.");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值