Java设置系统日期和时间

需求:利用java实现设置系统的日期和时间

一、代码Demo1

package com.xu.demo.test;

import java.io.IOException;

public class SetDateTime {

    public static void main(String[] args) {
        //Operating system name
        String osName = System.getProperty("os.name");
        String cmd = "";
        try {
            if (osName.matches("^(?i)Windows.*$")) {// Window 系统
                // 格式 HH:mm:ss
                cmd = "  cmd /c time 2:02:00";
                Runtime.getRuntime().exec(cmd);
                // 格式:yyyy-MM-dd
                cmd = " cmd /c date 2022-05-7";
                Runtime.getRuntime().exec(cmd);
            } else {// Linux 系统
                // 格式:yyyyMMdd
                cmd = "  date -s 20090326";
                Runtime.getRuntime().exec(cmd);
                // 格式 HH:mm:ss
                cmd = "  date -s 22:35:00";
                Runtime.getRuntime().exec(cmd);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

思路就是利用Java执行系统的命令行来设置系统时间,运行以后发现并没有设置成功,我们打开Windows的CMD窗口执行cmd /c time 2:02:00发现系统提示如下:

可以看到,上面的代码是无法完成我们的需求的,原因是我们Java代码只能获取到普通用户权限而无法获取到管理员权限,修改时间是需要先获得管理员权限才能执行设置日期和时间这样的危险操作,那接下来怎么办呢?我们继续看下面的代码

二、代码Demo2

package com.huawei.test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class RunBatTest {

    public static void main(String[] args) {
        setDateTimeBat();
    }

    public static void setDateTimeBat() {
        try {
            File temDir = new File("C:\timeTemp");
            String filePath = "setDateTime.bat";
            File batFile = new File(temDir.getPath() + "/" + filePath);

            if (!temDir.exists()) {
                temDir.mkdir();
                batFile.createNewFile();
            }

            FileWriter fw = new FileWriter(filePath);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("@echo off
");
            bw.write("%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
");
            bw.write("time 21:35:00");
            bw.newLine();
            bw.write("date 2022/04/28");
            //bw.write("date 2023/10/1");
            bw.close();
            fw.close();
            Process process = Runtime.getRuntime().exec(filePath);
            process.waitFor();
            //等上面的执行完毕后再删除文件
            batFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

可以看到,上面的代码采用了一种新的思路,创建了一个临时的Bat批处理文件,在批处理文件中写入一些命令行,其中下面这行可以让我们获得系统管理员权限

bw.write("%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit ");

下面两行就是常规的设置日期和时间,最后由java来执行这个Bat批处理文件,经过验证是能成功修改时间的。

bw.write("time 21:35:00"); bw.newLine(); //换行 bw.write("date 2022/04/28");

今天的内容到此为止,如果有什么疑问和错误地方欢迎各位网友在下面评论留言,本人看到后会第一时间回复和解疑,再次感谢。

经验分享 程序员 微信小程序 职场和发展