go_ntp/ntp.go
2024-05-10 21:55:26 +02:00

44 lines
1.1 KiB
Go

package go_ntp
import (
"fmt"
"time"
"github.com/beevik/ntp"
)
// GetDefaultServers returns the addresses of the four servers of the PTB (https://www.ptb.de/cms/)
func GetDefaultServers() []string {
return []string{
"ptbtime1.ptb.de",
"ptbtime2.ptb.de",
"ptbtime3.ptb.de",
"ptbtime4.ptb.de",
}
}
// GetCurrentTime returns either the current time of the first accessible NTP server
// or the current local time and an error
func GetCurrentTime(ntpServers ...string) (syncedTime time.Time, err error) {
if len(ntpServers) == 0 {
err = fmt.Errorf("no time servers defined")
return
}
for _, ntpServer := range ntpServers {
if syncedTime, err = ntp.Time(ntpServer); err == nil {
break
}
}
return
}
// GetLocalOffset returns either the difference between the current local time and the
// current time of the first accessible NTP server or an empty duration and an error
func GetLocalOffset(ntpServers ...string) (offset time.Duration, err error) {
var syncedTime time.Time
if syncedTime, err = GetCurrentTime(ntpServers...); err == nil {
offset = time.Until(syncedTime)
}
return
}