java实现修改linux系统时间(centos)

java实现修改linux系统时间(centos)

在这里插入图片描述

公司项目要求linux系统时间不准确,在web页面可以进行修改,如下:

1 思路

时间插件:wdatepicker

html页面

<input type="text" id="dateupdate" name="dateupdate" class="form-control" onclick="WdatePicker({dateFmt:'MM-dd-yyyy HH:mm:ss',minDate:'%y-%M-%d %H:%m:%s'})">
<button class="btn-blue" onclick="submitupdatetime()">提交</button>

js代码

function submitupdatetime() {
    
    
    var time = $("#dateupdate").val();
    if (time!=""||time!=null){
    
    
        $.ajax({
    
    
            url:"${ctx!}/admin/system/updateTime.do",
            type:"POST",
            cache:false,
            async:false,
            data:{
    
    "timevalue":time},
            success:function (data) {
    
    
              if (data=="1"){
    
    
                  alert("修改成功!");
                  window.location.reload();
              } else{
    
    
                  alert("修改失败!");
                  window.location.reload();
              }
            },
            error:function (jqXHR) {
    
    
                console.log(jqXHR)
            }
        });
    }
}

后台

 @RequestMapping("/updateTime")
   public@ResponseBody String updateTime(@RequestParam("timevalue")String timevalue){
    
    
       String result="0";
       if (StringUtils.isNotBlank(timevalue)){
    
    
           String[] split = timevalue.split(" ");
           if (split.length>0){
    
    
               try {
    
    
                   SynSystemDateUtils.updateSysDateTime(split[0],split[1]);
                   result="1";
               } catch (Exception e) {
    
    
                   e.printStackTrace();
               }
           }
       }
       return result;
   }
  1. 修改系统时间工具类

    package com.aio.util;
    
    import org.apache.commons.io.FileUtils;
    import java.io.*;
    import java.io.IOException;
    import java.util.Locale;
    import java.util.UUID;
    
    /**
     * @author:qiwentao
     * @creattime:2021-12-05 13:22
     */
    public class SynSystemDateUtils {
          
          
    
        public static void main(String[] args) {
          
          
            String date = "2017-11-11";
            String time = "11:11:11"  ;
            try {
          
          
                updateSysDateTime(date,time);
            } catch (Exception e) {
          
          
                e.printStackTrace();
            }
        }
    
        /**
         * 修改系统时间
         * yyyy-MM-dd HH:mm:ss
         */
        public static void updateSysDateTime(String dataStr_,String timeStr_) throws Exception {
          
          
            try {
          
          
                String osName = System.getProperty("os.name");
                // Window 系统
                if (osName.matches("^(?i)Windows.*$")) {
          
          
                    String cmd;
                    // 格式:yyyy-MM-dd
                    cmd = " cmd /c date " + dataStr_;
                    Runtime.getRuntime().exec(cmd);
                    // 格式 HH:mm:ss
                    cmd = " cmd /c time " + timeStr_;
                    String res = runAndResult(cmd);
                    System.out.println("windows 时间修改" + res);
                } else if (osName.matches("^(?i)Linux.*$")) {
          
          
                    // Linux 系统 格式:yyyy-MM-dd HH:mm:ss   date -s "2017-11-11 11:11:11"
                    FileWriter excutefw = new FileWriter("/usr/updateSysTime.sh");
                    BufferedWriter excutebw=new BufferedWriter(excutefw);
                    //excutebw.write("date -s \"" + dataStr_ +" "+ timeStr_ +"\"\r\n");
                    excutebw.write("date -s \"" + dataStr_ +" "+ timeStr_ +"\"\n");
                    excutebw.close();
                    excutefw.close();
                    String cmd_date ="sh /usr/updateSysTime.sh";
                    String res = runAndResult(cmd_date);
                    System.out.println("cmd :" + cmd_date + " date :" + dataStr_ +" time :" + timeStr_);
                    System.out.println("linux 时间修改" + res);
                } else {
          
          
                    System.out.println("操作系统无法识别");
                }
            } catch (IOException e) {
          
          
                e.getMessage();
            }
        }
    
    
    
        /**
         * 执行 脚本命令  关心结果
         * @param cmd
         * @return
         */
        public static String runAndResult(String cmd) throws Exception{
          
          
            StringBuilder sb = new StringBuilder();
            BufferedReader br = null;
            boolean execFlag = true;
            String uuid = UUID.randomUUID().toString().replace("-","");
            String tempFileName = "./temp" + uuid +".sh";
            try {
          
          
                String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
                if (osName.matches("^(?i)LINUX.*$") || osName.contains("MAC")) {
          
          
                    FileWriter excutefw = new FileWriter(tempFileName);
                    BufferedWriter excutebw=new BufferedWriter(excutefw);
                    excutebw.write(cmd + "\n");
                    excutebw.close();
                    excutefw.close();
                    String command ="bash " + tempFileName;
                    Process p = Runtime.getRuntime().exec(command);
                    p.waitFor();
                    br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line;
                    while ((line = br.readLine()) != null) {
          
          
                        sb.append(System.lineSeparator());
                        sb.append(line);
                    }
                    br.close();
                    br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                    while ((line = br.readLine()) != null) {
          
          
                        sb.append(System.lineSeparator());
                        sb.append(line);
                        if (line.length() > 0){
          
          
                            execFlag = false;
                        }
                    }
                    br.close();
                    if (execFlag){
          
          
                    }else {
          
          
                        throw new RuntimeException(sb.toString());
                    }
                }else {
          
          
                    throw new RuntimeException("不支持的操作系统类型");
                }
            } catch (Exception e) {
          
          
                throw e;
            }finally {
          
          
                if (br != null){
          
          
                    br.close();
                }
                FileUtils.deleteQuietly(new File(tempFileName));
            }
            return sb.toString();
        }
    }
    

效果图:

在这里插入图片描述

在linux终端查看修改的时间

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44975322/article/details/121730945
今日推荐