Skip to content

Instantly share code, notes, and snippets.

@xoba
Created July 12, 2014 11:46
Show Gist options
  • Save xoba/786498c950e1c92cc57f to your computer and use it in GitHub Desktop.
Save xoba/786498c950e1c92cc57f to your computer and use it in GitHub Desktop.
compare local to official us nist government time
package main
import (
"encoding/xml"
"fmt"
"net/http"
"os"
"time"
)
func main() {
start := time.Now()
t, err := GovernmentTime()
if err != nil {
fmt.Fprintf(os.Stderr, "oops, error getting time: %v\n", err)
os.Exit(1)
}
end := time.Now()
rt := end.Sub(start) / 2
mid := start.Add(rt)
fmt.Printf("local (%s) - government (%s) = %v\n", iso(mid), iso(t), mid.Sub(t))
}
func GovernmentTime() (time.Time, error) {
var t time.Time
resp, err := http.Get("http://time.gov/actualtime.cgi")
if err != nil {
return t, err
}
defer resp.Body.Close()
var x TimeXml
d := xml.NewDecoder(resp.Body)
if err := d.Decode(&x); err != nil {
return t, err
}
t = time.Unix(0, 1000*x.Time)
return t, nil
}
type TimeXml struct {
Time int64 `xml:"time,attr"`
}
func iso(t time.Time) string {
return t.Format("2006-01-02T15:04:05.000Z")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment