forked from visinsight/go_ntp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
systime.go
71 lines (55 loc) · 1.16 KB
/
systime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package ntp
import (
"errors"
"fmt"
"log"
"os/exec"
"runtime"
"time"
)
var ostype = runtime.GOOS
func linux(tm time.Time) error {
settime := fmt.Sprintf("date -s \"%d/%d/%d %02d:%02d:%02d.%03d\"",
tm.Year(), tm.Month(), tm.Day(),
tm.Hour(), tm.Minute(), tm.Second(),
time.Duration(tm.Nanosecond())/time.Millisecond)
log.Println(settime)
log.Println("set time to [", tm, "]")
cmd := exec.Command("/bin/bash", "-c", settime)
err := cmd.Run()
if err != nil {
return err
}
return nil
}
func win32(tm time.Time) error {
settime := fmt.Sprintf("date %d/%d/%d && time %02d:%02d:%02d.%02d",
tm.Year(), tm.Month(), tm.Day(),
tm.Hour(), tm.Minute(), tm.Second(),
time.Duration(tm.Nanosecond())/(10*time.Millisecond))
log.Println(settime)
log.Println("set time to [", tm, "]")
cmd := exec.Command("cmd.exe", "-c", settime)
_, err := cmd.CombinedOutput()
if err != nil {
return err
}
return nil
}
// 设置时间到os
func SetTimeToOs(tm time.Time) error {
switch ostype {
case "windows":
{
return win32(tm)
}
case "linux":
{
return linux(tm)
}
default:
{
return errors.New("not support local host os " + ostype)
}
}
}