doumangzhen7204 2018-02-21 04:54
浏览 456
已采纳

如何通过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 05: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()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部