Skip to content

Instantly share code, notes, and snippets.

@kunalkushwaha
Created April 16, 2015 12:05
Show Gist options
  • Save kunalkushwaha/1100a411bf960c22fb08 to your computer and use it in GitHub Desktop.
Save kunalkushwaha/1100a411bf960c22fb08 to your computer and use it in GitHub Desktop.
Fetch time from timeapi.org and set to system, Alternative to ntp
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"bytes"
"os/exec"
)
func main() {
month := map[string]string{
"01": "JAN",
"02": "FEB",
"03": "MAR",
"04": "APR",
"05": "MAY",
"06": "JUN",
"07": "JUL",
"08": "AUG",
"09": "SEP",
"10": "OCT",
"11": "NOV",
"12": "DEC",
}
res, err := http.Get("http://www.timeapi.org/utc/now")
if err != nil {
log.Fatal(err)
}
date, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
// 2015-04-16T10:29:50+00:00
// date -s "2 OCT 2006 18:00:00"
DateTime := strings.SplitN(string(date), "T", 2)
YYYY_DD_MM := strings.SplitN(DateTime[0], "-", 3)
Time := strings.SplitN(DateTime[1], "+", 2)
time_cmd := fmt.Sprintf("\"%s %s %s %s\"", YYYY_DD_MM[2], month[YYYY_DD_MM[1]], YYYY_DD_MM[0], Time[0])
fmt.Println(time_cmd)
cmd := exec.Command("/bin/date","-s",time_cmd)
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment