doumangzhen7204 2018-02-21 12:54
浏览 444
已采纳

如何通过go syscall设置系统日期和时间

I am trying to set the linux system time and date with a go syscall, but I always get an invalid date error. When i execute the call on the terminal with the presumably wrong date it always ends successful.

This is my test code:

package main

import (
    "os/exec"
    "time"
    "os"
    "syscall"
    "fmt"
)

func main() {
    fiveDaysFromNow := time.Now().Add(time.Hour * 24 * 5)
    err := SetSystemDate(fiveDaysFromNow)
    if err != nil {
        fmt.Printf("Error: %s", err.Error())
    }
}

func SetSystemDate(newTime time.Time) error {
    binary, lookErr := exec.LookPath("date")
    if lookErr != nil {
        fmt.Printf("Date binary not found, cannot set system date: %s
", lookErr.Error())
        return lookErr
    } else {
        //dateString := newTime.Format("2006-01-2 15:4:5")
        dateString := newTime.Format("2 Jan 2006 15:04:05")
        fmt.Printf("Setting system date to: %s
", dateString)
        args := []string{"--set", dateString}
        env := os.Environ()
        return syscall.Exec(binary, args, env)
    }
}

And the output I get is:

Setting system date to: 26 Feb 2018 13:36:52

--set: invalid date ‘26 Feb 2018 13:36:52’

Process finished with exit code 1

Executing in the terminal:

date -s '26 Feb 2018 13:36:52'

nevertheless succeeds without any problems.

I am testing this on Ubuntu 16.04.3 LTS with KDE installed, but this will be used on an embedded device with an custom Yocto Yogurt image. Will there be any difference?

Do i need to use different formatting for the date string when using syscall.Exec()?

  • 写回答

1条回答 默认 最新

  • duanbi8529 2018-02-21 13:11
    关注

    @JimB and @Tim Cooper you are right using os/exec works like a charm...

    This is now the updated function:

    func SetSystemDate(newTime time.Time) error {
        _, lookErr := exec.LookPath("date")
        if lookErr != nil {
            fmt.Printf("Date binary not found, cannot set system date: %s
    ", lookErr.Error())
            return lookErr
        } else {
            //dateString := newTime.Format("2006-01-2 15:4:5")
            dateString := newTime.Format("2 Jan 2006 15:04:05")
            fmt.Printf("Setting system date to: %s
    ", dateString)
            args := []string{"--set", dateString}
            return exec.Command("date", args...).Run()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料