github.com/mem/u-root@v2.0.1-0.20181004165302-9b18b4636a33+incompatible/cmds/timesos/service.go (about) 1 // Copyright 2018 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "os/exec" 9 "strconv" 10 "syscall" 11 "time" 12 ) 13 14 type TimeService struct { 15 Date string 16 Time string 17 } 18 19 func getCurrentDate() string { 20 return time.Now().Format("2006-01-02") 21 } 22 23 func getCurrentTime() string { 24 return time.Now().Format("15:04") 25 } 26 27 func parseDate(d TimeJsonMsg) time.Time { 28 // split date message into integers for each field 29 YYYY, _ := strconv.Atoi(d.Date[:4]) 30 MM, _ := strconv.Atoi(d.Date[5:7]) 31 DD, _ := strconv.Atoi(d.Date[8:]) 32 33 hh, _ := strconv.Atoi(d.Time[:2]) 34 mm, _ := strconv.Atoi(d.Time[3:]) 35 36 return time.Date(YYYY, time.Month(MM), DD, hh, mm, 0, 0, time.UTC) 37 } 38 39 // Update sets the TimeService fields to the current system time 40 func (ts *TimeService) Update() { 41 ts.Date = getCurrentDate() 42 ts.Time = getCurrentTime() 43 } 44 45 // AutoSetTime calls the ntpdate u-root command to get 46 // the current date from time.google.com 47 func (ts TimeService) AutoSetTime() error { 48 return exec.Command("ntpdate").Run() 49 } 50 51 // ManSetTime sets the system time similarly to u-root's "date" command with 52 // user-entered fields 53 func (ts TimeService) ManSetTime(new TimeJsonMsg) error { 54 userTime := parseDate(new) 55 tv := syscall.NsecToTimeval(userTime.UnixNano()) 56 if err := syscall.Settimeofday(&tv); err != nil { 57 return err 58 } 59 return nil 60 } 61 62 // NewTimeService builds a TimeService with the current system date and time 63 func NewTimeService() (*TimeService, error) { 64 return &TimeService{ 65 Date: getCurrentDate(), 66 Time: getCurrentTime(), 67 }, nil 68 }